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
add
function takes one argumenta
and returns another function.The returned function takes the second argument
b
and returns the sum ofa
andb
.add5
is a new function created by partially applyingadd
witha = 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
curry
function takes a functionfn
and 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
fn
with 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:
calculateDiscount
is a curried function that takes adiscount
and returns a function to apply that discount to aprice
.tenPercentDiscount
andtwentyPercentDiscount
are specialized functions created by partially applyingcalculateDiscount
.