Example 1: Manual Currying
function add(a) {
return function(b) {
return a + b;
};
}
const add5 = add(5); // Partially apply the function with `a = 5`
console.log(add5(3)); // Output: 8 (5 + 3)
In this example:
The
addfunction takes one argumentaand returns another function.The returned function takes the second argument
band returns the sum ofaandb.add5is a new function created by partially applyingaddwitha = 5.
Example 2: Generalized Currying Function
You can create a utility function to curry any function dynamically:
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
} else {
return function(...moreArgs) {
return curried.apply(this, args.concat(moreArgs));
};
}
};
}
// Example usage
function sum(a, b, c) {
return a + b + c;
}
const curriedSum = curry(sum);
console.log(curriedSum(1)(2)(3)); // Output: 6
console.log(curriedSum(1, 2)(3)); // Output: 6
console.log(curriedSum(1)(2, 3)); // Output: 6
In this example:
The
curryfunction takes a functionfnand returns a curried version of it.The curried function checks if the number of arguments passed (
args.length) is greater than or equal to the number of parameters expected byfn(fn.length).If enough arguments are provided, it calls the original function
fnwith those arguments.If not, it returns a new function that waits for the remaining arguments.
Example 3: Currying with Arrow Functions (ES6)
You can also use arrow functions to make currying more concise:
const add = a => b => a + b;
const add5 = add(5);
console.log(add5(3)); // Output: 8
Use Cases for Currying
Partial Application: Pre-fill some arguments to create specialized functions.
Function Composition: Combine smaller functions to build more complex ones.
Reusability: Create reusable utility functions with fixed parameters.
Example 4: Real-World Use Case
// Curried function to calculate discounts
const calculateDiscount = discount => price => price * (1 - discount);
const tenPercentDiscount = calculateDiscount(0.1);
const twentyPercentDiscount = calculateDiscount(0.2);
console.log(tenPercentDiscount(100)); // Output: 90
console.log(twentyPercentDiscount(100)); // Output: 80
In this example:
calculateDiscountis a curried function that takes adiscountand returns a function to apply that discount to aprice.tenPercentDiscountandtwentyPercentDiscountare specialized functions created by partially applyingcalculateDiscount.