CURRYING
Currying is an advanced technique of working with functions. It’s used not only in JavaScript, but in other languages as well.
Currying is a transformation of functions that translates a function from callable as f(a, b, c)
into callable as f(a)(b)(c)
.
Currying doesn’t call a function. It just transforms it.
Let’s see an example first, to better understand what we’re talking about, and then practical applications.
We’ll create a helper function curry(f)
that performs currying for a two-argument f
. In other words, curry(f)
for two-argument f(a, b)
translates it into a function that runs as f(a)(b)
:
funcfunction curry(f) { // curry(f) does the currying transform
return function(a) { return function(b) { return f(a, b); }; };}tion 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 curriedSum = curry(sum); alert( curriedSum(1)(2) ); // 3
As you can see, the implementation is straightforward: it’s just two wrappers.
- The result of
curry(func)
is a wrapperfunction(a)
. - When it is called like
curriedSum(1)
, the argument is saved in the Lexical Environment, and a new wrapper is returnedfunction(b)
. - Then this wrapper is called with
2
as an argument, and it passes the call to the originalsum
.
More advanced implementations of currying, such as _.curry from lodash library, return a wrapper that allows a function to be called both normally and partially:
function sum(a, b) { return a + b; } let curriedSum = _.curry(sum); // using _.curry from lodash library alert( curriedSum(1, 2) ); // 3, still callable normally alert( curriedSum(1)(2) ); // 3, called partially
Comments
Post a Comment