Curry - Problem

Given a function fn, return a curried version of that function.

A curried function is a function that accepts fewer or an equal number of parameters as the original function and returns either another curried function or the same value the original function would have returned.

In practical terms, if you called the original function like sum(1,2,3), you would call the curried version like csum(1)(2)(3), csum(1)(2,3), csum(1,2)(3), or csum(1,2,3). All these methods of calling the curried function should return the same value as the original.

Input & Output

Example 1 — Basic Sum Function
$ Input: fn = function sum(a, b, c) { return a + b + c; }
Output: Curried version that can be called as curry(1)(2)(3) or curry(1, 2)(3), etc.
💡 Note: The curried function accumulates arguments until it has 3 parameters, then calls sum(1, 2, 3) = 6
Example 2 — Partial Application
$ Input: fn = function multiply(x, y) { return x * y; }
Output: curry(2)(5) or curry(2, 5) both return 10
💡 Note: Can be called with all arguments at once or one at a time, always returns 2 * 5 = 10
Example 3 — Single Parameter
$ Input: fn = function identity(x) { return x; }
Output: curry(42) returns 42 immediately
💡 Note: Since function only needs 1 parameter, curried version executes immediately when given 1 argument

Constraints

  • 1 ≤ fn.length ≤ 10
  • 0 ≤ arguments.length ≤ 1000
  • Function will be called with valid arguments

Visualization

Tap to expand
Curry - Closure-Based Currying INPUT Original Function function sum(a, b, c) { return a + b + c; } Parameters: 3 a b c Call Examples: curry(1)(2)(3) curry(1, 2)(3) curry(1)(2, 3) curry(1, 2, 3) All return same result! ALGORITHM STEPS 1 Create Curried Wrapper Return curried function 2 Collect Arguments Accumulate in closure 3 Check Arg Count Compare with fn.length 4 Return Result or Curry Execute or continue Implementation function curry(fn) { return function curried (...args) { if(args.length >= fn.length) return fn(...args); return (...more) --> curried(...args,...more) FINAL RESULT Execution: curry(1)(2)(3) curry(1) args: [1], need 3 curried(2) args: [1,2], need 3 curried(3) args: [1,2,3], OK! Result: 6 1 + 2 + 3 = 6 OK - All calls return 6 Key Insight: Closures preserve accumulated arguments between calls. Each partial application returns a new function that "remembers" previous args via closure scope. When total args >= fn.length, execute original fn. This enables flexible calling: curry(1)(2)(3), curry(1,2)(3), curry(1)(2,3), or curry(1,2,3) all work! TutorialsPoint - Curry | Closure-Based Currying Approach
Asked in
Google 15 Facebook 12
23.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen