Currying
Currying is a technique where a function that takes multiple arguments is transformed into a sequence of functions, each taking a single argument. That gives us partial application, and it makes functions more modular and reusable.
Understanding Currying
Let’s start with a basic example of a function that makes a sundae:
function makeSundae(base, topping) {
return `Here is your ${base} ice cream with ${topping}!`;
}
const sundae = makeSundae("vanilla", "hot fudge");
console.log(sundae);
Now, let’s transform this function using currying:
function makeCurriedSundae(base) {
return function (topping) {
return `Here is your ${base} ice cream with ${topping}!`;
};
}
const vanillaSundae = makeCurriedSundae("vanilla");
const chocolateSundae = makeCurriedSundae("chocolate");
console.log(chocolateSundae("hot fudge"));
console.log(vanillaSundae("chocolate syrup"));
In this version, makeCurriedSundae is a curried function. It first takes one argument, the base flavor, and returns another function that expects the topping. So we can make specialized functions out of one general function.
Practical Example of Currying
Here is a more practical use of currying:
function makeLog(base) {
return function (value) {
return Math.log(value) / Math.log(base);
};
}
const log10 = makeLog(10);
const log2 = makeLog(2);
console.log(log10(100)); // Output: 2
console.log(log2(8)); // Output: 3