Currying is a technique in functional programming — transformation of the function of multiple arguments into several functions of a single argument in sequence.
// From This
function calculate(a, b, c) {
return a + b + c;
}
calculate(1, 2, 3); // 6
// To this
const calculateCurried = (a) => {
return (b) => {
return (c) => {
return a + b + c;
}
}
}
calculateCurried(1)(2)(3) // 6
Currying is useful when we want to create new functions from an existing one by pre-filling some arguments. For example, from a general multiply function we can create double and triple:
const multiply = (a) => (b) => a * b;
const double = multiply(2);
const triple = multiply(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15