Let me abstract it into a different application. Put another way,
// Don't worry about this, it's just a function that takes a bunch or parameters and adds them up.
const addThemUp = (...nums) => nums.reduce((a, c) => a + c)
const partial = (fn, ...argsToApply) => {
return (...restArgsToApply) => {
return fn(...argsToApply, ...restArgsToApply)
}
}
const func1 = partial(addThemUp, 1, 2, 3)
console.log(func1);
// This returns a function.
// It is analogous to
// (...restArgsToApply) => {
// return addThemUp(1, 2, 3, ...restArgsToApply)
// }
const sum = func1(4, 5, 6);
console.log(sum);
// This returns the sum, 21.
// It is analogous to going
// (...restArgsToApply) => {
// return addThemUp(1, 2, 3, 4, 5, 6)
// }
// and calling it with (4, 5, 6) as parameters so really it is
// addThemUp(1, 2, 3, 4, 5, 6)
The second line is the hardest part to understand: what …restArgsToApply is taking?
It is part of that second function, the one that is in func1:
// (...restArgsToApply) => {
// return addThemUp(1, 2, 3, ...restArgsToApply)
// }
It is the rest operator. It is saying, “I don’t care how many parameters are sent, just scoop them all up and put them in an array.” It’s doing the same thing as the rest operator in the first line. The difference is when. The rest operator in the first line is getting run when partial is called and that returns a function that has that second line as the first line of the returned function. That spread operator won’t get run until the returned function (the one stored in func1) gets run. It just sits there.
So, when we get to line 3 (of the partial function), we have two arrays (from the rest operators) that get spread out - instead of arrays, they are now lists of parameters.
It may seem odd to use the rest operator and then immediately undo it with the spread operator, but it’s actually a really handy and clean way to deal with variable numbers of parameters. It looks weird at first, but you get used to it.
Additionally, this thing of functions returning partial functions is a confusing subject - cut yourself some slack. Seriously, don’t worry if this is hard. Just do your best and maybe look up some youtube videos on “javascript curried function”. But don’t worry if it isn’t clear right away. I do this all the time and sometimes I still have to stop and look at it twice.