I\'ve seen references to curried functions in several articles and blogs but I can\'t find a good explanation (or at least one that makes sense!)
Currying is translating a function from callable as f(a, b, c)
into callable as f(a)(b)(c)
.
Otherwise currying is when you break down a function that takes multiple arguments into a series of functions that take part of the arguments.
Literally, currying is a transformation of functions: from one way of calling into another. In JavaScript, we usually make a wrapper to keep the original function.
Currying doesn’t call a function. It just transforms it.
Let’s make curry function that performs currying for two-argument functions. In other words, curry(f)
for two-argument f(a, b)
translates it into f(a)(b)
function curry(f) { // curry(f) does the currying transform
return function(a) {
return function(b) {
return f(a, b);
};
};
}
// usage
function sum(a, b) {
return a + b;
}
let carriedSum = curry(sum);
alert( carriedSum(1)(2) ); // 3
As you can see, the implementation is a series of wrappers.
curry(func)
is a wrapper function(a)
.sum(1)
, the argument is saved in the Lexical Environment, and a new wrapper is returned function(b)
.sum(1)(2)
finally calls function(b)
providing 2, and it passes the call to the original multi-argument sum.