AniUI Academy

Curry a function of fixed arity

mediumFunctions & Closures+250 XPPractice

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 works
const add = curry((a, b) => a + b);
const add5 = add(5);

add5(1); // 6
add5(2); // 7 — the partial is reusable, no leaked state

A 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.length is reached, then invoke fn.
  • 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.length is 0.
Asked atMetaMicrosoftAtlassian

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.