AniUI Academy
medium+250 XPPractice

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 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.

Your workspace

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.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.