Explorer
JavaScript

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

<p>Write a function <code>curry(fn)</code> that returns a curried version of fn. The curried function can be called with one argument at a time until all arguments are provided.</p>

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

šŸ’” Hint 1: Currying transforms f(a,b,c) into f(a)(b)(c). šŸ’” Hint 2: Accumulate arguments until you have enough to call the original function. šŸ’” Hint 3: Check args.length >= fn.length. If yes, call fn. Otherwise, return a new function that collects more args.

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

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (currying transforms f(a,b,c) into f(a)(b)(c)).
  3. Implement Logic: Handle state and transformations efficiently (accumulate arguments until you have enough to call the original function).
  4. 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

Time Complexity O(1) wrapper invocation overhead
Space Complexity O(1) closure scope retention

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.

Curry Function

Hard

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.

Example Scenarios
1Example 1
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.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
[6,6,6]