Currying
Currying is a transformation of functions that translates a function from callable as f(a, b, c) into callable as f(a)(b)(c).
Currying doesn't call a function. It just transforms it.
1. The Concept
A curried function takes the first argument and returns a new function that takes the second argument, which returns a new function that takes the third argument, and so on, until all arguments are fulfilled.
2. Basic Example
Normal Function:
function add(a, b) {
return a + b;
}
console.log(add(1, 2)); // 3
Curried Function:
function curriedAdd(a) {
return function(b) {
return a + b;
};
}
// Arrow function version
const curriedAddArrow = a => b => a + b;
console.log(curriedAdd(1)(2)); // 3
3. Why use Currying?
Partial Application
You can fix some arguments and create a new, specialized function.
function log(date, importance, message) {
console.log(`[${date.getHours()}:${date.getMinutes()}] [${importance}] ${message}`);
}
// Curried version manually
const curriedLog = date => importance => message => log(date, importance, message);
// Fix the date
const logNow = curriedLog(new Date());
// Fix the importance
const logErrorNow = logNow("ERROR");
logErrorNow("Something went wrong");
Composition
Currying makes it easier to compose small functions into bigger ones.
4. Advanced Implementation
You can write a helper function to curry any function automatically.
programming/javascript/vanilla/javascript programming/javascript/vanilla/closures programming/javascript/vanilla/call-apply-bind