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); // 6Hints (5)
- Use
func.lengthto get the number of expected arguments. - Return the result when collected args >= expected args.
- Otherwise return a new function that concatenates new args with existing.
- Use recursion or closure to accumulate arguments across calls.
- Remember to preserve
thiscontext usingapply.
Topics
- Functional Programming
Asked at
Google · Amazon · Stripe · Bloomberg
