JavaScript Currying
JavaScript currying is a technique used to transform a function that takes multiple arguments into a sequence of functions that each take a single argument. The resulting functions can be called individually, or the entire sequence can be called as a single function, with each argument supplied one at a time.
To put it simply, currying is like breaking down a complex function into smaller, simpler functions that can be composed together.
Here’s an example of a function that takes two arguments and returns their sum:
function add(a, b) {
return a + b;
}
To curry this function, we can use a higher-order function that returns a new function that expects one argument at a time:
function add(a) {
return function(b) {
return a + b;
};
}
This function can now be used like this:
const add2 = add(2); // returns a function that expects one argument
const result = add2(3); // returns 5
Here, we first create a new function add2
by passing the first argument 2
to the add
function. This returns a new function that expects the second argument. We then call add2
with the second argument 3
, which returns the result 5
.
Currying can also be achieved using ES6 arrow functions:
const add = a => b => a + b;
const add2 = add(2);
const result = add2(3); // returns 5
Here, we use arrow functions to create the curried function add
. The function add
takes one argument a
and returns another arrow function that takes one argument b
and returns the sum of a
and b
. We can then use this function in the same way as the previous example.
Currying can be a powerful technique when used appropriately. It can help to simplify complex functions, increase code re-usability, and enable easier function composition.