Currying is a technique in functional programming where a function that takes multiple arguments is transformed into a sequence of functions, each taking a single argument. This allows for functions to be more modular and reusable.
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 makeSundae(base) {
return function (topping) {
return `Here is your ${base} ice cream with ${topping}!`;
}
}
const vanillaSundae = makeSundae("vanilla");
const chocolateSundae = makeSundae("chocolate");
console.log(chocolateSundae("hot fudge"));
console.log(vanillaSundae("chocolate syrup"));
In this version, makeSundae
is a curried function. It first takes one argument, the base flavor, and returns another function that expects the topping. This setup is very flexible and allows you to create more specific functions based on a general function.
Here’s how you might use currying in a more practical scenario:
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
This example demonstrates currying a function to create new functions for logarithms with different bases.