Problem Statement
What is currying in JavaScript?
Explanation
Currying transforms a function that takes multiple arguments into a sequence of functions that each take a single argument.
Instead of calling function with all arguments at once, you call it with one argument, which returns another function that takes the next argument, and so on.
Currying enables partial application and function composition.
It makes functions more reusable and flexible.
Currying is common in functional programming.
You can curry functions manually or use libraries like Lodash.
Code Solution
SolutionRead Only
// Regular function
function add(a, b, c) {
return a + b + c;
}
console.log(add(1, 2, 3)); // 6
// Curried version
function addCurried(a) {
return function(b) {
return function(c) {
return a + b + c;
};
};
}
console.log(addCurried(1)(2)(3)); // 6
// Arrow function currying (cleaner)
const addArrow = a => b => c => a + b + c;
console.log(addArrow(1)(2)(3)); // 6
// Partial application with currying
const add5 = addArrow(5);
console.log(add5(3)(2)); // 10
const add5and3 = add5(3);
console.log(add5and3(7)); // 15
// Practical example - greeting
const greet = greeting => name => time => {
return `${greeting} ${name}, good ${time}!`;
};
const sayHello = greet('Hello');
const sayHelloToJohn = sayHello('John');
console.log(sayHelloToJohn('morning')); // 'Hello John, good morning!'
console.log(sayHelloToJohn('evening')); // 'Hello John, good evening!'
// Reusable specialized functions
const greetFormally = greet('Good day');
const greetCasually = greet('Hey');
console.log(greetFormally('Sir')('afternoon'));
console.log(greetCasually('Buddy')('night'));
// Generic curry function
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
}
return function(...nextArgs) {
return curried.apply(this, args.concat(nextArgs));
};
};
}
// Use curry helper
function multiply(a, b, c) {
return a * b * c;
}
const curriedMultiply = curry(multiply);
console.log(curriedMultiply(2)(3)(4)); // 24
console.log(curriedMultiply(2, 3)(4)); // 24
console.log(curriedMultiply(2)(3, 4)); // 24
console.log(curriedMultiply(2, 3, 4)); // 24