Partial Application and Currying in Javascript
1. Partial application
Involves fixing a certain number of arguments of a function and producing a new function that takes the remaining arguments
function multiply(a, b, c) {
return a * b * c;
}
// Partially apply the multiply function
const multiplyByTwo = multiply.bind(null, 2);
// Now, the new function only requires one argument
const result = multiplyByTwo(3, 4); // Equivalent to multiply(2, 3, 4)
console.log(result); // Output: 24
2. Currying
Currying is the process of transforming a function that takes multiple arguments into a sequence of functions that each take a single argument
function curryMultiply(a) {
return function(b) {
return function(c) {
return a * b * c;
};
};
}
// Usage of curried function
const result = curryMultiply(2)(3)(4); // Equivalent to multiply(2, 3, 4)
console.log(result); // Output: 24