Implement Curry Function

HardFunctional Programming20 min4 tests

Implement a curry function that transforms a function to allow partial application.

Requirements

  • Transform a function to accept arguments one at a time
  • Return the result when all arguments are provided
  • Support passing multiple arguments at once
  • Preserve the function's arity (number of expected arguments)

Example

const add = (a, b, c) => a + b + c;
const curriedAdd = curry(add);
curriedAdd(1)(2)(3); // 6
curriedAdd(1, 2)(3); // 6
curriedAdd(1)(2, 3); // 6
Hints (5)
  1. Use func.length to get the number of expected arguments.
  2. Return the result when collected args >= expected args.
  3. Otherwise return a new function that concatenates new args with existing.
  4. Use recursion or closure to accumulate arguments across calls.
  5. Remember to preserve this context using apply.

Topics

  • Functional Programming

Asked at

Google · Amazon · Stripe · Bloomberg

Join Us
blur