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 of fixed arity, where the arity is fn.length. It returns a function that 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, and the call that reaches or exceeds fn.length invokes fn with all collected arguments and returns its result. A single call may supply several arguments at once, so f(1, 2)(3), f(1)(2, 3) and f(1, 2, 3) are all equivalent. A partially applied function can be reused: calling it twice with different arguments must not mix them up. If fn takes no arguments at all, the very first call invokes it.

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.

Where it's been asked

  • Meta
  • Microsoft
  • Atlassian

From public interview reports — a problem very like this one has shown up in a round at these companies. Not an exhaustive list.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

Need a nudge?

Reveal a conceptual hint or the reference solution. Both were written and reviewed with the problem — no runtime magic.

Discussion

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

No comments yet. Be the first to say something.