I am trying to learn decorators in javascript with the help of this article: https://dev.to/logrocket/understanding-javascript-decorators-ba2.
My questions are:
- How is it possible that in
Validator
function we can read arguments ofMultiply
function? - Why
Multiply
arguments are undefined before thereturn function(...args)
inside theValidator
function?
Here is the code:
let Multiply = (...args) => {
return args.reduce((a, b) => a * b)
}
// validated integers
const Validator = (fn) => {
return function(...args) {
const validArgs = args.every(arg => Number.isInteger(arg));
if (!validArgs) {
throw new TypeError('Argument cannot be a non-integer');
}
return fn(...args);
}
}
//decorated multiply function that only multiplies integers
MultiplyValidArgs = Validator(Multiply);
MultiplyValidArgs(6, 8, 2, 10);
Validator creates and returns a new function (specified in the body
function(...args) { ...}
)...args
is the array of all parameters that will be given to that function when called. And it's this list of parameters that is inspected by the returned function, (not by theValidator
function) In the end the created function will call the initial function, given as a parameter toValidator
, provided all parameters are numbersSo there are three functions involved:
1 the initial function
Multiply
2 the
Validator
function, that can create a new function wrapping the initial function3 the returned and function
MultiplyValidArgs
that you can use