Currying in JavaScript …
Currying refers to the process of transforming a function with multiple arguments into the same function with less arguments. Curry effect is achieved by binding some of the arguments to the first function invoke.
lets jump into code usage
function sum(a,b,c) { //regular function
return a+b+c;
}
how curry function looks like
function sum(a) {
return function (b) {
return function (c ){
return a + b + c;
}}}
find the difference between two sum functions sum(1,2,3) and sum(1)(2)(3).
Advanced Usage of Currying
const curryFun = function(uncurried) {
const parameters = Array.prototype.slice.call(arguments, 1);
return function() {
return uncurried.apply(this, parameters.concat(
Array.prototype.slice.call(arguments, 0)
));
};
};var greeter = function(greeting, separator, emphasis, name) {
console.log(greeting + separator + name + emphasis);
};var greetHello = curryFun(greeter, “Hello”, “, “, “.”);
greetHello(“Vasu”);var greetGoodDay = curryFun(greeter, “Good day”, “, “);
greetGoodDay(“.”, “Vasu”);
You can reuse and maintain readability of JavaScript functions.
One thing that’s important to keep in mind when currying is the order of the arguments.
Currying is an incredibly useful technique from functional JavaScript. It allows you to generate a library of small, easily configured functions that behave consistently, are quick to use, and that can be understood when reading your code.