FrontendInterviews.dev

Loading problem…

44. Curry Function

Medium•
Acceptance: 100.00%
•
🔓3/3 Pro unlocks today

Implement curry - convert a function into a curried version based on fn.length (its declared arity).

Requirements

1) Input

  • Accept a function fn.

2) Curried behavior

  • Return a function that can collect arguments across multiple calls.
  • Each call may provide one or more arguments.
  • Once collected argument count is at least fn.length, invoke fn and return its result.

3) Invocation policy

  • Use fn.length as the required argument count.
  • If extra arguments are provided on the final call, still invoke normally.
  • Preserve dynamic this from the call that finally triggers execution.

4) Arity-0 edge case

  • For fn.length === 0, the curried function should execute on the first invocation.

Examples

const add3 = (a, b, c) => a + b + c
const cAdd3 = curry(add3)

cAdd3(1)(2)(3)     // 6
cAdd3(1, 2)(3)     // 6
cAdd3(1)(2, 3)     // 6
cAdd3(1, 2, 3, 4)  // 6 (extra args allowed)

Constraints

  • Accumulate arguments across calls until collected count reaches fn.length.
  • Allow one or many arguments per partial call.
  • Invoke when collected count is >= fn.length (not only ===).
  • Use dynamic this from the invocation that triggers final execution.