1

I am practising ES6 and I have this code:

const over = (...fns) => (...args) =>
  fns.map(fn => fn.apply(null, args));

const minMax = over(Math.min, Math.max);

console.log(minMax(1, 2, 3, 4, 5));
console.log(minMax(1, 2, 5, 4, 3));
console.log(minMax(1, 2, 5, -4, 3));

The goal is to get the minimum and the maximun values between the numbers passed as arguments.

I could understand almost everything, the dynamic is very clear, with one exception, I know that args refers to the parameters coming from minMax(), but I couldn't get how the code recognize it.

My guess is: since we have two functions, over() and minMax(), when called, they are automatically read in this order, that is why the code knows that the first anonymous function refers to over() and the second one to minMax(). But this is just a guess, I don't know if I am right.

What is exactly happening here?

Berg_Durden
  • 1,531
  • 4
  • 24
  • 46
  • 1
    Take a look at [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) and [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). – Jens Jan 15 '20 at 13:11
  • 1
    `minMax = over(Math.min, Math.max)`, so, kind of, `minMax = (...args) => [Math.min, Math.max].map(fn => fn.apply(null, args));`. From there, `minMax(1, 2, 3, 4, 5)` is `[Math.min, Math.max].map(fn => fn.apply(null, [1, 2, 3, 4, 5]))` – ASDFGerte Jan 15 '20 at 13:13
  • 1
    `over` is a function which takes a list of functions (as `fns`) and *returns a function which takes a list of values (as `args`).* `minMax` is this *function which takes a list of values*, because it's the return value of `over`. `minMax` now, when called, maps the list of functions over the list of values. – deceze Jan 15 '20 at 13:13
  • 1
    Always think in terms of "is a function which takes X and returns Y". And remember that `(..) => (..) => ..` is shorthand for *"function which returns a function"*. – deceze Jan 15 '20 at 13:16
  • @deceze That is exactly what I wasn't getting, the 'return' part. It is very clear now. Thank you very much. If you want to edit your comment as an answer I would be happy to accept it. – Berg_Durden Jan 15 '20 at 13:18
  • 1
    Replace `(..) => ..` with `function (..) { return .. }` to perhaps make that clearer. – deceze Jan 15 '20 at 13:20

0 Answers0