← All tasksJavaScript · Middle

curry: currying

Write a function curry(fn) that turns a multi-argument function into a chain of calls. Arguments can be passed one by one or in groups: add(1)(2)(3), add(1, 2)(3) and add(1, 2, 3) all give the same result.

Once as many arguments have been collected as fn declares (fn.length), fn itself is called. A partially applied function can be called many times.

Tests (4)

  1. const add = curry((a, b, c) => a + b + c);
    expect(add(1)(2)(3)).toBe(6);
  2. const add = curry((a, b, c) => a + b + c);
    expect(add(1, 2)(3)).toBe(6);
    expect(add(1)(2, 3)).toBe(6);
    expect(add(1, 2, 3)).toBe(6);
  3. const add = curry((a, b) => a + b);
    const add1 = add(1);
    expect(add1(10)).toBe(11);
    expect(add1(20)).toBe(21);
  4. const join = curry((a, b, c) => [a, b, c].join('-'));
    expect(join('x')('y')('z')).toBe('x-y-z');