Problem Description
Given a function fn, implement a curry function that returns a curried version of fn. The curried function gathers arguments over multiple calls (e.g. fn(a)(b)(c), fn(a, b)(c), fn()(a, b, c)) until the total number of provided parameters reaches the original function’s arity, at which point it invokes fn and returns its result.
Key Insights
- The curried function must handle accumulations of arguments across multiple invocations.
- The function checks if the number of collected arguments is equal to or exceeds fn's parameter count.
- Once enough arguments have been collected (fn.length), fn is invoked with them.
- The solution must work even if arguments are provided in groups or with empty calls.
Space and Time Complexity
Time Complexity: O(n), where n is the number of arguments processed, as each call simply aggregates arguments.
Space Complexity: O(n), to store the cumulative arguments across invocations.
Solution
We implement a closure that accumulates provided arguments. Each time the returned function is called, it aggregates new arguments with those from previous calls. When the total number of arguments reaches the original function's arity, we invoke fn with these arguments. This is achieved by defining an inner function that captures the accumulated arguments in its closure. The main idea is to check the number of collected arguments and either return a new function waiting for more arguments or return the final computed result by calling fn.