Sub topic 10
Currying
This chapter assumes you are comfortable with closures, higher-order functions, and rest/spread syntax from the earlier chapters.
Currying turns a function that takes several arguments into a chain of functions that each take one. A curried add(a, b, c) becomes add(a)(b)(c). Each call returns a new function that remembers the arguments supplied so far, using a closure, until it has all of them and computes the result.
Why curry at all?
Currying lets you pass a function only some of its arguments and get back a specialized function to use later. This fits well with map, filter, and composition helpers, because they expect functions of a single argument.
// Manually curried
const hasRole = (role) => (user) => user.roles.includes(role);
const prop = (key) => (obj) => obj[key];
const users = [
{ name: 'Ada', roles: ['admin'] },
{ name: 'Linus', roles: ['dev'] },
{ name: 'Grace', roles: ['admin', 'dev'] }
];
const adminNames = users.filter(hasRole('admin')).map(prop('name'));
console.log(adminNames); // [ 'Ada', 'Grace' ]Put the data argument last. Configuration such as role or key goes first, so you can fix it early and leave the data for later.
A generic curry helper
Writing nested arrows by hand gets tedious. A helper can curry any function based on its declared arity. Arity is the number of parameters a function declares, which JavaScript exposes as fn.length.
const curry = (fn) => {
const curried = (...args) =>
args.length >= fn.length
? fn(...args)
: (...more) => curried(...args, ...more);
return curried;
};
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)); // 6This helper is "loose": it accepts one or more arguments per call. Strict currying allows exactly one argument per call.
Common errors
`fn.length` can be wrong
Default parameters, and every parameter after one, are left out of fn.length. Rest parameters are not counted at all.
console.log(((a, b = 1) => a + b).length); // 1
console.log(((...xs) => xs.length).length); // 0A function with arity 0 runs right away when curried, and a function with defaults runs too early. In these cases, curry with an explicit arity or write the nested arrows yourself.
Passing a curried function straight to `map`
map calls its callback with (element, index, array). A loose curried function accepts all three arguments.
const curry = (fn) => {
const curried = (...args) =>
args.length >= fn.length ? fn(...args) : (...more) => curried(...args, ...more);
return curried;
};
const add = curry((a, b) => a + b);
console.log([1, 2, 3].map(add(10))); // [ 11, 12, 13 ]
console.log([1, 2, 3].map(add)); // [ 1, 3, 5 ] (element + index!)Always supply the configuration arguments before you hand the function to map.
Losing `this`
The helper calls fn without a receiver, so currying an object method breaks any use of this. Curry standalone functions only, or bind the method first.
Exercise
Using the curry helper, write a curried between(min, max, n) that returns true when min <= n <= max, then use it to keep only the numbers from 10 to 20 in [5, 12, 18, 25].
Show answer
const between = curry((min, max, n) => n >= min && n <= max); console.log([5, 12, 18, 25].filter(between(10, 20))); // [ 12, 18 ]. Because filter passes (n, index, array), the extra arguments go to fn but are ignored, since fn only reads its first three parameters.
Exercise
Why does curry((a, b = 2) => a * b)(5) return 10 rather than a function?
Show answer
Because of the default value, fn.length is 1. The first call already supplies 1 argument, so the helper runs fn(5), and b falls back to 2.