Could someone explain how this function works? I'm studying currying (I do not know what Spanish translation you will have) and in a part of the book it teaches this function as a general curry function (or a general curry function).
I find it hard to understand the methods that it calls over the array in the second and fourth lines. The call
method is not unique to functions? Should not pass a start and end arguments of slice
?
Also, it is not assumed that the arguments
object can not be called from nested functions?
function curry(func) {
var fixedArgs = [].slice.call(arguments,1);
return function() {
args = fixedArgs.concat([].slice.call(arguments))
return func.apply(null, args);
};
}
To understand it, the author gives an example of its use. Still, I can not fully understand how it works. But I transcribe it here:
This can now be applied to a more standard divider () function that returns the result of dividing its two arguments:
function divider(x,y) {
return x/y;
}
divider(10,5);
<< 2
The curry () function can be used to create a more specific function that finds the reciprocal of numbers:
reciprocal = curry(divider,1);
<< function () {
args = fixedArgs.concat([].slice.call(arguments))
return func.apply(null, args);
}
reciprocal(2);
<< 0.5
In case someone helps you to understand it and be able to answer my question, I leave the book and its author below: JavaScript: Novice to Ninja - Darren Jones
EDIT : I begin to understand it. In line 2, call ( call
) the function slice
and pass it as arguments the object arguments (as it is the first argument and as the function indicates call
will be the object on which the function is applied, that is, where the internal structure of slice
has a this.
) and 1, that being the second index, the function that is passed as an argument to curry
will be skipped. Then all the rest of the arguments passed to curry
will be added to an array that is the variable fixedArgs
.
When the function curry
was called, it will return another function that are the 4 and 5 line. In this function, we call again slice
through call
and since there is only one argument (which is the object arguments
), all the arguments passed to this new function will be added to the variable fixedArgs
( by concat
and then to variable args
.
Finally the function will return the call (through apply
) of the function originally passed as argument of curry
with all arguments within args
.
And to generalize and define it in a more theoretical way:
The curry
function, as expressed here, allows to call a function without the totality of its arguments, which will then return another function that waits for the remaining arguments in its invocation.