Skip to main content

Search

Search problems, hooks, and pages

Curry a Function

Implement curry(fn) that transforms a function taking multiple arguments into a sequence of functions each taking a single argument (or some of them). curriedSum(1)(2)(3) and curriedSum(1, 2)(3) should both return the same result. This is a classic closures + higher-order-function interview question.

Examples

Input: curry(sum)(1)(2)(3) where sum = (a, b, c) => a + b + c
Output: 6
// Arguments are collected one at a time until the original arity (3) is met, then sum runs.
Input: curry(sum)(1, 2)(3)
Output: 6
// Multiple arguments can be passed in a single call; currying still fills the remaining slots.

Constraints

  • Respect the original function arity via fn.length.
  • Preserve the original this context when finally invoking fn.
  • Allow arguments to be supplied across any number of calls.
closurehigher-order-functionrecursionfunctional-programming

Important

Interview Tip

Start with the fixed-arity version using fn.length and recursion. Mention the placeholder variant (lodash _.curry) for out-of-order args as a follow-up, and the infinite-currying trick (call with () to terminate) when arity is unknown. Be ready to contrast currying with partial application: currying always produces a chain of single-argument functions — f(a)(b)(c) — whereas partial application fixes some arguments up front and returns a function taking the rest, e.g. const add5 = add.bind(null, 5). Both build on closures and enable point-free composition.

Approach: Fixed Arity

Collect arguments across calls; once the count reaches fn.length, invoke the original function. The standard interview answer.

Complexity

Time: O(n)Space: O(n)

Pros

  • Simple recursive logic
  • Respects original arity
  • Handles both (1)(2)(3) and (1, 2)(3)

Cons

  • Requires a fixed, known arity (fn.length)
  • No out-of-order argument support