Curry Polyfill
FunctionalPolyfill
Implement curry(fn) that returns a curried version of fn.
Requirements:
- Use
fn.lengthto determine the target arity - Return a function that keeps accumulating arguments across calls
- Invoke
fnas soon as total collected arguments ≥fn.length - Support any mix of arities per call:
f(a)(b)(c),f(a,b)(c),f(a)(b,c)
Examples
Example 1
Input
const sum = (a, b, c) => a + b + c;
const c = curry(sum);
console.log(c(1)(2)(3));
console.log(c(1, 2)(3));
console.log(c(1)(2, 3));Output
6
6
6Explanation
All three calling styles produce the same result once three arguments are collected.
Notes
- `fn.length` counts declared parameters — it does not count rest parameters (`...args`)
Hints
Editorial: Curry Polyfill
Implementing curry from scratch
Currying transforms f(a, b, c) into a chain where arguments can be supplied in any grouping: f(a)(b)(c), f(a, b)(c), f(a)(b, c). It keeps collecting arguments until it has enough to call the original function.
What the interviewer checks
- Do you use
fn.length(the declared arity) to know when to invoke? - Do you accumulate arguments correctly across multiple calls?
Implementation
function curry(fn) { return function curried(...args) { if (args.length >= fn.length) { return fn.apply(this, args); } return function (...nextArgs) { return curried.apply(this, [...args, ...nextArgs]); }; }; }
How it works
fn.length is the number of declared parameters. This is the arity target.
Each call to the curried function either:
- Has enough args (
args.length >= fn.length) → invokesfndirectly - Needs more args → returns a new function that merges the accumulated args with the new ones and recurses
const sum = (a, b, c) => a + b + c; const curriedSum = curry(sum); // fn.length === 3 curriedSum(1)(2)(3); // 1 call with 1 arg, 2nd with 1, 3rd triggers invoke → 6 curriedSum(1, 2)(3); // 1 call with 2 args, 2nd triggers invoke → 6 curriedSum(1)(2, 3); // 1 call with 1 arg, 2nd with 2 triggers invoke → 6
Why fn.length and its limits
fn.length counts declared parameters, excluding rest parameters. A function like f(...args) has length === 0, which breaks this pattern. That's fine — mention it and say currying only makes sense for functions with a fixed arity.
Edge cases to mention
fn.length === 0→curried()invokes immediately on the first call with no args- Extra arguments beyond
fn.lengthare passed through tofnunchanged thiscontext is preserved across the chain via.apply(this, ...)
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it