Hai what is function Currying , Curried Functions 😳 ya ... it's sound like spicy 💁 ,there are actually some useful .
oke .. We will start from the basics what are functions
Function is something they simply take input from one side processes inside give output from another side
input ->([processes])-> Output
Consider a simple function add two number
let add = (x,y)=>x+y
console.log(add(1,2))
3
Let's curve the function add()
Using currying, a function is transformed from being callable as f(a, b, c) to being callable as f(a)(b)(c).
Is it correct that add(x,y) should be transformed into add(x)(y)? 🥸
Yes 👍 Currying is when you break down a function that takes multiple arguments into a series of functions that each take only one argument.
Lets Code ..
function curry(f) { // curry(f) does the currying transform
return function(x) {
return function(y) {
return f(x, y);
};
};
}
function add(x,y){
return x+y;
}
let curriedAdd=curry(add)
console.log(curriedAdd(1)(2))
3
😳 why it called Curried
Maybe fist method you added some salt second one added some spice third some water .. 😂 ya it helps to call a method as multiple parts like
let c =curriedAdd(5)
c(3)
8
You can see that the implementation is straightforward: it's just two wrappers.
- The result of curry(func) is a wrapper function(x)
- When it is called like curriedSum(1), the argument is saved in the Lexical Environment, and a new wrapper is returned function(y).
- The wrapper is then called with 2 as an argument, and it passes the call to the original sum.
Uses of currying function
a) It helps to avoid passing same variable again and again.
b) It is extremely useful in event handling.
Top comments (2)
Awesome 👌
thank you