Write a function `curry(fn)` that returns a curried version of fn. The curried function can be called with one argument at a time until all arguments are provided.
Problem Statement
Examples
Input: const curriedAdd = curry((a, b, c) => a + b + c); curriedAdd(1)(2)(3)
Output: 6
Explanation: Can be called one argument at a time.
Complexity
Time Complexity: O(1)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
To solve Curry Function, we consider the execution characteristics of JavaScript engines. Write a function `curry(fn)` that returns a curried version of fn. The curried function can be called with one argument at a time until all arguments are provided. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.
Step-by-Step Approach
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (currying transforms f(a,b,c) into f(a)(b)(c)).
- Implement Logic: Handle state and transformations efficiently (accumulate arguments until you have enough to call the original function).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
}
return function(...nextArgs) {
return curried.apply(this, args.concat(nextArgs));
};
};
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Empty or boundary inputs (empty arrays, strings, zero length).
- Type checks and unexpected values (e.g.
null,undefined, negative numbers). - Closure preservation and memory isolation between separate invocations.