Currying is a technique of writing function having multiple arguments, into sequence of functions with single argument. Thus it keep returning the function until all the fucntions are exhausted, arguments are remembered via Closure.
Don't know about Closure, then ignore it ;)
Let go through this simple example:
// without arguments
let dish = function () {
return function () {
console.log("Chicken Curry ;) ");
};
};
dish()();
// console
// Chicken Curry ;
// with arguments
let dish = function () {
return function (y) {
console.log(y);
};
};
dish()("I had crush on JS");
// console
// I had crush on JS
let multiply = function (x) {
return function (y) {
console.log(x*y);
};
};
dish(2)(3);
// console
// 6
Now a complex example
let employee =
name =>
role =>
company =>
name + " is a " +
role + " in " +
company
let output = employee('Jack')('Frontend Engineer')('Google')
console.log(output)
// console
// Jack is a Frontend Engineer in Google
// we can also write it as
let person = employee('Jack')
let designation = person('Frontend Engineer')
console.log(designation('Google'))
// console
// Jack is a Frontend Engineer in Google
Benefits
- It will make out function look sleek when it has multiple arguments
- I avoids the frequent calling of a function with the same argument, Let's see how
We have a function to calculate the volume of a cylinder
It happens that all the cylinders in your house are of height 100m.
function volume(l, w, h) {
return l * w * h;
}
volume(200,30,100); // 600,000l
volume(32,45,100); //144000l
volume(2322,232,100); // 53870400l
We are repeatedly using the same height in all 3 invocations.
Let's solve this using currying
function volume(h) {
return (w) => {
return (l) => {
return l * w * h
}
}
}
const hCylinderHeight = volume(100);
hCylinderHeight(200)(30); // 600,000l
hCylinderHeight(32)(45); //144000l
hCylinderHeight(2322)(232); // 53,870,400l
Top comments (0)