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
Validatorfunction we can read arguments ofMultiplyfunction? - Why
Multiplyarguments are undefined before thereturn function(...args)inside theValidatorfunction?
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) { ...})...argsis 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 theValidatorfunction) 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
Multiply2 the
Validatorfunction, that can create a new function wrapping the initial function3 the returned and function
MultiplyValidArgsthat you can use