Sub topic 10
Currying
This chapter assumes you are comfortable with closures, higher-order functions, and the pipe helper from the previous chapter. All examples run as-is in Node.js 18 or later.
What currying is
Currying turns a function that takes several arguments into a chain of functions that each take one argument. A curried function takes the first argument and returns a function that waits for the second, which returns a function that waits for the third, and so on until every argument has arrived. Then the original body runs.
// Regular function: all arguments at once
const add3 = (a, b, c) => a + b + c;
// Curried by hand: one argument per call
const add3Curried = (a) => (b) => (c) => a + b + c;
console.log(add3(1, 2, 3)); // 6
console.log(add3Curried(1)(2)(3)); // 6
const addTen = add3Curried(10); // waits for b
const addTenAndFive = addTen(5); // waits for c
console.log(addTenAndFive(1)); // 16Closures make this work. Each returned arrow function closes over the arguments supplied so far, so addTen remembers a = 10 and addTenAndFive remembers both a and b.
Why curry at all
Currying lets you build specialized functions out of general ones. It also fits composition well. pipe and compose pass one value from stage to stage, so every stage must be a unary function, meaning a function that takes one argument. A curried function with all but its last argument supplied is exactly that.
This has a consequence for how you design signatures: put the data last. If the configuration arguments (the key, the predicate, the mapping function) come first, you can fix them early and get back a unary function that waits for the data.
A generic curry helper
Writing nested arrows by hand gets tedious. A helper can curry any function by reading its declared arity, meaning the number of parameters it declares, from 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)); // 6
console.log(add3(1, 2, 3)); // 6This helper is "loose": each call may supply one argument or several. Strict currying in languages like Haskell allows only one argument per call. The loose version is the JavaScript norm, and libraries such as Ramda and Lodash's _.curry behave this way.
Partial results are reusable
Each step builds a new array with spread ([...args, ...more]) and never mutates the saved one. That means you can branch from one partial result many times without the branches interfering:
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);
const add10 = add3(10);
console.log(add10(1)(2)); // 13
console.log(add10(5)(5)); // 20
console.log(add10(0, 0)); // 10If the helper had used args.push(...) instead, the second call would see arguments left over from the first. Immutability matters even inside a utility this small.
Currying in a pipeline
Here are data-last, curried versions of common operations combined with pipe:
const curry = (fn) => {
const curried = (...args) =>
args.length >= fn.length
? fn(...args)
: (...more) => curried(...args, ...more);
return curried;
};
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
const prop = curry((key, obj) => obj[key]);
const map = curry((fn, xs) => xs.map(fn));
const filter = curry((pred, xs) => xs.filter(pred));
const join = curry((sep, xs) => xs.join(sep));
const activeNames = pipe(
filter(prop('active')),
map(prop('name')),
join(', ')
);
const users = [
{ name: 'Ada', active: true },
{ name: 'Linus', active: false },
{ name: 'Grace', active: true }
];
console.log(activeNames(users)); // Ada, GraceEvery stage is a general function with its configuration already supplied. The pipeline describes what happens without naming a single intermediate variable.
Gotchas
`fn.length` is not always what you expect
The helper trusts fn.length, and several parameter forms change it:
| Declaration | `fn.length` |
|---|---|
| `(a, b, c) => {}` | 3 |
| `(a, b = 2) => {}` | 1 |
| `(a, ...rest) => {}` | 1 |
| `(...args) => {}` | 0 |
| `({ a, b }) => {}` | 1 |
Parameters with default values, and every parameter after the first default, are not counted. Rest parameters are never counted. The result is that a curried function can run earlier than you intended:
const curry = (fn) => {
const curried = (...args) =>
args.length >= fn.length
? fn(...args)
: (...more) => curried(...args, ...more);
return curried;
};
const greet = curry((greeting, name = 'friend') => `${greeting}, ${name}`);
console.log(greet('Hello')); // Hello, friend (ran immediately, no function returned)
// Fix: state the arity explicitly
const curryN = (n, fn) => {
const curried = (...args) =>
args.length >= n
? fn(...args)
: (...more) => curried(...args, ...more);
return curried;
};
const greet2 = curryN(2, (greeting, name = 'friend') => `${greeting}, ${name}`);
console.log(typeof greet2('Hello')); // function
console.log(greet2('Hello')('Ada')); // Hello, AdaExtra arguments from callbacks fill empty slots
Array methods pass more than one argument to their callbacks. map passes (element, index, array). With a loose curry, those extras land in whichever parameters are still empty, and you get a wrong answer with no error:
const curry = (fn) => {
const curried = (...args) =>
args.length >= fn.length
? fn(...args)
: (...more) => curried(...args, ...more);
return curried;
};
const scale = curry((factor, offset, x) => x * factor + offset);
// Bug: forgot offset. map supplies (el, index, array),
// so offset = el and x = index.
console.log([1, 2, 3].map(scale(10))); // [ 1, 12, 23 ]
// Fix 1: supply every argument except the data
console.log([1, 2, 3].map(scale(10, 0))); // [ 10, 20, 30 ]
// Fix 2: force the callback to be unary
const unary = (fn) => (x) => fn(x);
console.log([1, 2, 3].map(unary(scale(10, 0)))); // [ 10, 20, 30 ]Losing `this`
The helper calls fn(...args) with no receiver, so a curried method loses its this. Curry standalone functions, not object methods. If you must curry a method, bind it first: curry(obj.method.bind(obj)). Be careful here, because a bound function's length drops by the number of arguments you bound.
Readability and cost
Every partial step allocates a closure and an argument array. In ordinary application code this overhead does not matter, but in a hot loop that runs millions of times it can show up in profiles. The more common cost is readability. A call like f(a)(b)(c) with no names in between is hard to follow, and stack traces show anonymous arrow functions. Give partial results meaningful names (const byActive = filter(prop('active'))) and curry the functions you actually reuse, not every function.
Currying versus partial application
Currying is a transformation of a function's shape: one call per argument, until the arguments run out. Partial application fixes some arguments of a function now and returns a function that takes the rest. A curried function makes partial application easy, but the two are separate ideas, and you can partially apply a function that was never curried. The next chapter covers partial application on its own terms.
Exercise
Using the curry helper from this chapter, what does the following code print, and why? const sub = curry((a, b) => a - b); console.log([5, 6].map(sub(1)));
Show answer
It prints [ -4, -5 ]. map calls sub(1)(el, index, array). That supplies 4 arguments, which is at least fn.length of 2, so fn runs with a = 1 and b = el. The results are 1 - 5 = -4 and 1 - 6 = -5. The extra index and array arguments are ignored because the body only reads a and b. If you wanted el - 1, the parameter order is wrong for a data-last style: define it as curry((b, a) => a - b) instead.
Exercise
Write a curried, data-last function replace(pattern, replacement, str) and use it with pipe to build a function slugify that lowercases a string, trims it, and replaces runs of whitespace with a hyphen. slugify(' Hello Big World ') should return 'hello-big-world'.
Show answer
const replace = curry((pattern, replacement, str) => str.replace(pattern, replacement)); const toLower = (s) => s.toLowerCase(); const trim = (s) => s.trim(); const slugify = pipe(trim, toLower, replace(/\s+/g, '-')); console.log(slugify(' Hello Big World ')); prints hello-big-world. Trimming before the replace step matters. Otherwise the leading and trailing spaces would become hyphens at the ends of the slug.
Exercise
A teammate curries const log = (level, ...messages) => console.log(level, ...messages) with the curry helper and finds that log('warn') prints immediately instead of returning a function. Explain the cause and give a fix.
Show answer
Rest parameters are not counted in fn.length, so log.length is 1. The call log('warn') supplies 1 argument, which meets the arity check, so the function runs at once. Fix it with curryN(2, log) so the helper waits for at least one message. Another option is to avoid currying variadic functions and write const warn = (...m) => log('warn', ...m).