CodePark/ problems / curry
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Closures and higher-order functions

curry

hardabout 30 minutes in an interview

Implement curry(fn). It returns a function that collects arguments over one or more calls. It calls fn once it has enough arguments.

  • "Enough" means at least fn.length arguments. fn.length is the number of parameters fn declares.
  • Each call may pass any number of arguments: c(1)(2)(3), c(1, 2)(3) and c(1, 2, 3) all work.
  • While there aren't enough arguments, return a new function that keeps collecting. Calling it with no arguments adds nothing.
  • A partial result can be reused. For example, after const add10 = c(10), the calls add10(1)(2) and add10(5, 5) give two independent results.
  • When enough arguments arrive, call fn with all of them and return its result.
  • If fn.length is 0, the first call runs fn.
Input: const add = curry((a, b, c) => a + b + c); add(1)(2)(3) Output: 6
Input: add(1, 2)(3) Output: 6
Input: const add10 = add(10); add10(1)(2); add10(5, 5); Output: 13, 20