How to implement currying?

A generic curry(fn) returns a function that collects arguments across calls and invokes the original function once it has received at least fn.length arguments; until then it returns another function waiting for the rest.

The algorithm

  1. Read the target arity from fn.length.
  2. Return a function curried(...args).
  3. If args.length >= arity, call fn with those arguments (keeping this).
  4. Otherwise return a new function that, when called with more arguments, calls curried with the old and new arguments combined.

This version accepts several arguments per step, so add(1)(2)(3), add(1, 2)(3) and add(1)(2, 3) all work. That is what libraries like Lodash and Ramda do.

Edge cases to mention in an interview

  • fn.length ignores rest parameters and parameters with defaults, so curry((a, b = 2) => ...) thinks the arity is 1. Allow an explicit arity: curry(fn, arity).
  • Variadic functions (like sum(...nums)) cannot be curried by length. A common variant collects until it is called with no arguments: sum(1)(2)(3)().
  • Placeholders (Lodash's _) let you skip arguments; an optional extension.
  • Preserve this by using apply.

Why it matters

Curried helpers make configuration-first functions (log("error")(message)), point-free pipelines, and reusable predicates (hasRole("admin")) easy to create.

Code example

js
1function curry(fn, arity = fn.length) {
2 return function curried(...args) {
3 if (args.length >= arity) return fn.apply(this, args);
4 return (...more) => curried.apply(this, [...args, ...more]);
5 };
6}
7
8const add3 = curry((a, b, c) => a + b + c);
9console.log(add3(1)(2)(3), add3(1, 2)(3), add3(1)(2, 3), add3(1, 2, 3)); // 6 6 6 6
10
11// Reusable, configuration-first helpers
12const hasRole = curry((role, user) => user.roles.includes(role));
13const isAdmin = hasRole("admin");
14const users = [{ name: "Ada", roles: ["admin"] }, { name: "Linus", roles: ["user"] }];
15console.log(users.filter(isAdmin).map((u) => u.name)); // ["Ada"]
16
17// Explicit arity for functions with defaults
18const greet = curry((greeting, name = "friend") => `${greeting}, ${name}!`, 2);
19console.log(greet("Hello")("Ada")); // Hello, Ada!
20
21// Variadic version: keep collecting until called with no arguments
22function curryVariadic(fn) {
23 const collect = (args) => (...more) => (more.length ? collect([...args, ...more]) : fn(...args));
24 return collect([]);
25}
26const sum = curryVariadic((...nums) => nums.reduce((a, b) => a + b, 0));
27console.log(sum(1)(2)(3, 4)()); // 10

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app