Curry a function of fixed arity
Currying is how you build specialised helpers out of general ones: a formatCurrency(locale, currency, amount) becomes formatCurrency("en-IN")("INR"), a single-argument formatter you can hand to map. It is also the interview question that separates people who have internalised closures from people who have read about them.
Implement curry(fn) for a function whose arity is fn.length. The returned function collects arguments across as many calls as it takes. Each call that has not yet gathered fn.length arguments returns another function that waits for more; the call that reaches or exceeds fn.length invokes fn with every collected argument and returns the result.
Arguments
fnFunction- A function of fixed arity, inferred from
fn.length.
Returns
Function — A curried version of fn that can be invoked incrementally — one argument at a time or several at once.
Examples
const add = curry((a, b, c) => a + b + c);
add(1)(2)(3); // 6 — one at a time
add(1, 2)(3); // 6 — any grouping works
add(1, 2, 3); // 6 — all at once also worksconst add = curry((a, b) => a + b);
const add5 = add(5);
add5(1); // 6
add5(2); // 7 — the partial is reusable, no leaked stateA partially applied function can be called repeatedly without the arguments bleeding across calls.
What it has to do
- Collect arguments one at a time until
fn.lengthis reached, then invokefn. - Accept several arguments in a single call, in any grouping.
- Let a partially applied function be reused without leaking arguments between uses.
- Handle an arity of one, and invoke immediately when
fn.lengthis0.
Stuck? The javascript course covers everything this challenge needs.
- 1.takes one argument at a time
- 2.accepts any grouping of arguments
- 3.a partial application is reusable
- 4.handles an arity of one
- 5.invokes immediately for a zero-arity function
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.