⚡Flashcard Drill➔
NeetCode #953LC-2632MediumJavaScript
← Back to All Problems

#953 · #2632 · Curry(柯里化)

📌 Problem Statement & Constraints

Given a function fn, return its curried version: it may be called with one argument at a time or several at once, and it executes fn only once the accumulated argument count reaches fn.length.

💡 Core Algorithmic Approaches

  1. fn.length gives the number of declared parameters, which is the threshold for execution.
  2. Collect arguments recursively: each call concatenates the new arguments with the ones already gathered.
  3. When the accumulated count is at least fn.length, invoke fn(...args) and return the result.
  4. Otherwise return a function that keeps accepting arguments, preserving the currying behaviour.

💻 Benchmark Python3 Implementation

var curry = function(fn) {
    return function curried(...args) {
        if (args.length >= fn.length) {
            return fn(...args);               // enough arguments -> invoke
        }
        return (...next) => curried(...args, ...next);   // keep collecting
    };
};

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(1) per call, excluding the final fn invocation.
💾 Space Complexity
O(k): the accumulated argument array.

⚠️ Interview Pitfalls & Follow-ups

  • Hard-coding the parameter count: currying must key off the original function's fn.length.
  • Only supporting one argument per call: curried(1, 2) must be able to accumulate several at once.
  • Executing fn while arguments are still short: the result would be undefined instead of a waiting function.
  • Relying on the arguments object: it is not bound inside arrow functions; rest parameters are the correct tool.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related JavaScript Problems