coding round · ~15 min
JavaScriptintermediate

Implement curry

Write curry(fn) that returns a curried version of fn. The curried function collects arguments over any number of calls, in any grouping. Once it has received at least fn.length arguments, it calls fn with all of them and returns the result; until then it returns a function that waits for more.

  • with const add = curry((a, b, c) => a + b + c), the calls add(1)(2)(3), add(1, 2)(3), add(1)(2, 3) and add(1, 2, 3) all return 6
  • add()(1)()(2, 3) → 6 (a call with no arguments just returns a function)
  • const add1 = add(1): add1(2)(3) → 6 and add1(10)(20) → 31

Every partial application must be reusable: calling it again with different arguments must not affect earlier or later calls.

Define curry in the editor. 6 tests will call it.

solution.js
function curry(fn) {
  // fn.length is the number of parameters fn expects.
  // Keep collecting arguments until you have that many, then call fn.
}

Tests⌘/Ctrl + Enter to run

accepts one argument at a time
accepts all arguments at once
accepts mixed groupings
returns a function until enough arguments arrive
partial applications are reusable and independent
calls the original function once, with all the arguments
esc