JavaScriptMedium
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
- Read the target arity from
fn.length. - Return a function
curried(...args). - If
args.length >= arity, callfnwith those arguments (keepingthis). - Otherwise return a new function that, when called with more arguments, calls
curriedwith 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.lengthignores rest parameters and parameters with defaults, socurry((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
thisby usingapply.
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}78const 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 61011// Reusable, configuration-first helpers12const 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"]1617// Explicit arity for functions with defaults18const greet = curry((greeting, name = "friend") => `${greeting}, ${name}!`, 2);19console.log(greet("Hello")("Ada")); // Hello, Ada!2021// Variadic version: keep collecting until called with no arguments22function 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.