problem in concept of javascript decorators

114 views Asked by At

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:

  1. How is it possible that in Validator function we can read arguments of Multiply function?
  2. Why Multiply arguments are undefined before the return function(...args) inside the Validator 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);
1

There are 1 answers

0
Arjan On BEST ANSWER

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 the Validator function) In the end the created function will call the initial function, given as a parameter to Validator, provided all parameters are numbers

So there are three functions involved:

1 the initial function Multiply

2 the Validator function, that can create a new function wrapping the initial function

3 the returned and function MultiplyValidArgs that you can use