Currying function is a popular technique in functional programming, and it’s an essential concept to master when writing JavaScript code. Currying function is a way to transform a function with multiple arguments into a sequence of functions that each take a single argument. In other words, currying converts a function of N arguments into a chain of N functions that each take one argument.
Currying is useful in many situations where you need to create specialized versions of a function. For example, suppose you have a function that adds two numbers together:
function add(a, b) {
return a + b;
}
Now, imagine that you want to create a specialized version of the add
function that always adds a certain number to the input value. You could achieve this with currying:
function addN(n) {
return function(m) {
return n + m;
}
}
const add3 = addN(3);
console.log(add3(7)); // Output: 10
In this example, addN
is a curried version of add
. It returns a new function that takes a single argument m
and returns the sum of n
and m
. When you call addN(3)
, you get a new function that always adds 3
to its input value.
Another advantage of currying is that it can simplify the process of creating partial functions. A partial function is a function that is pre-configured with some of its arguments. For example, suppose you have a function that takes three arguments:
function multiply(a, b, c) {
return a * b * c;
}
Now, imagine that you want to create a specialized version of the multiply
function that always multiplies the first two arguments by a certain number. You could use currying to create a partial function like this:
function multiplyPartial(n) {
return function(a, b) {
return multiply(n, a, b);
}
}
const multiplyBy5 = multiplyPartial(5);
console.log(multiplyBy5(2, 3)); // Output: 30
In this example, multiplyPartial
is a curried version of multiply
. It returns a new function that takes two arguments a
and b
, and calls multiply
with the pre-configured value n
and the two input arguments. When you call multiplyPartial(5)
, you get a new function that always multiplies its first two arguments by 5
.
In JavaScript, you can use the bind
method to create a curried version of a function. For example, you can rewrite the addN
function like this:
function addN(n) {
return function(m) {
return n + m;
}
}
const add3 = addN.bind(null, 3);
console.log(add3(7)); // Output: 10
In this example, addN.bind(null, 3)
creates a new function that takes a single argument m
, and calls addN
with the pre-configured value 3
and the input argument m
. The first argument to bind
is the value of this
inside the function, which is not used in this case.
Currying is a powerful technique that can help you write more concise and reusable code. By breaking down a function with multiple arguments into a series of functions with single arguments, you can create specialized and partial functions that are easier to understand and maintain.