Currying!?
revanthrev23
Posted on June 5, 2021
I am sure we all know what currying is, in JavaScript. If not don't worry I have got you covered here.
A lot of people know the theory of currying, but not a lot of them, can implement the same. Implementing currying is extremely simple!
So what is currying?
Currying is a technique of evaluating function with multiple arguments, into a sequence of functions having lesser number of arguments.
Let's say a function can take in 3 arguments, we can curry this function, into a sequence of 3 functions taking 1 argument each, or into 2 functions taking 2 and 1 arguments each. So basically when we curry a function, we reduce the number of arguments it takes in, but still performs all the actions it was intended to.
I am sure you will understand this better with this piece of code.
//Function 1
const sum = function (a) {
return function (b) {
if (b) {
return sum(a+b);
}
return a;
}
};
//Function 2
function num_sum(a, b){
return a+b;
}
num_sum(1,2);
sum(1)(2)(3)..(n);
Function 2 is a traditional way of adding 2 numbers. Function 1 is the curried version of the same function where, we have reduced the number of arguments it has, in each function. Currying uses many concepts like high-order functions, where we can return a function or assign it to a value or even pass it as an argument to another function!
Let me show you another variant of currying the same sum function:
function sum(a,b){
return a + b;
}
function curry(f){
return function(a){
return function(b){
return f(a,b);
}
}
}
let curriedSum = curry(sum);
let ans = curriedSum(1)(2);
In this example, we are currying an already existing function. Basically, by doing this we can re-use it with various number of arguments at different parts of a program depending on our needs.
Advantages of Currying:
1) Currying helps you to avoid passing the same variable again and again.
2) It helps to create a higher order function. It extremely helpful in event handling.
3) Little snippets of code can be written and reused with ease.
Posted on June 5, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 20, 2024