Sub topic 13
Partial Application and Currying
This chapter assumes you already know what a closure is and that closures capture variables from the scope where a function was created. You should also be comfortable with rest parameters (...args) and spread syntax.
Fixing Arguments Ahead of Time
Partial application means calling a function with some of its arguments now and getting back a new function that takes the rest later. Closures make this possible, because the returned function remembers the arguments you already supplied.
function multiply(a) {
return function (b) {
return a * b;
};
}
const double = multiply(2);
console.log(double(5)); // 10
console.log(multiply(3)(4)); // 12Calling multiply(2) creates a new lexical environment where a is 2. The inner function closes over that environment, so double keeps a even after multiply has returned.
A Reusable `partial` Helper
You don't need to write every function in nested form. A general helper can pre-fill arguments for any function:
function partial(fn, ...preset) {
return function (...later) {
return fn(...preset, ...later);
};
}
function greet(greeting, name) {
return `${greeting}, ${name}!`;
}
const sayHello = partial(greet, 'Hello');
console.log(sayHello('Ada')); // Hello, Ada!The preset array lives in the closure. Each call to partial creates a separate preset, so separate partially applied functions don't interfere with each other.
Currying
Currying turns a function that takes several arguments into a chain of functions that each take one argument: f(a, b, c) becomes f(a)(b)(c). The multiply example above is curried by hand. A helper can curry any function with a fixed number of parameters:
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn(...args);
}
return (...more) => curried(...args, ...more);
};
}
const add3 = curry((a, b, c) => a + b + c);
console.log(add3(1)(2)(3)); // 6
console.log(add3(1, 2)(3)); // 6
console.log(add3(1)(2, 3)); // 6Each intermediate function closes over the args collected so far. Once enough arguments have been collected, the original function runs. This helper is lenient: it also accepts several arguments per call. Strict currying allows only one argument per call.
| Technique | Input | Result |
|---|---|---|
| Partial application | Some arguments now | One function that takes the rest |
| Currying | One argument per call | A chain of functions until all are supplied |
Common Errors
- Relying on
fn.lengthwith defaults or rest parameters.fn.lengthcounts only the parameters before the first one that has a default value or is a rest parameter. For(a, b = 1) => a + bit is1, socurryruns the function after the first argument. - Forgetting the final call.
add3(1)(2)returns a function, not a number. If you log it, you see a function where you expected a result. - Losing
this. The helpers above callfndirectly. If you pass in a method, bind it first withobj.method.bind(obj). - Expecting a snapshot of objects. Preset arguments are references. If you mutate a preset object later, the partially applied function sees the change.
Exercise
Given const add = curry((a, b = 10) => a + b);, what does add(5) return, and why?
Show answer
It returns 15, not a function. The default value on b makes fn.length equal 1, so curry sees enough arguments after the first call and runs the function with b set to its default of 10.
Exercise
Using partial, create logError from function log(level, msg) { return [${level}] ${msg}; } so that logError('disk full') returns "[ERROR] disk full".
Show answer
const logError = partial(log, 'ERROR');. The closure stores 'ERROR' in preset, and the later call adds 'disk full' as the second argument.