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 callsadd(1)(2)(3),add(1, 2)(3),add(1)(2, 3)andadd(1, 2, 3)all return6 add()(1)()(2, 3)→6(a call with no arguments just returns a function)const add1 = add(1):add1(2)(3)→6andadd1(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.
Hint 1fn.length tells you how many parameters fn declares.
Hint 2Return a function that takes ...args. If args.length is at least fn.length, call fn with them; otherwise return a new function that combines args with the next call's arguments.
Hint 3Never push into one shared array. Build a fresh array with [...args, ...more] on each call, so partial applications stay independent.
one clean solution
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
}
return (...more) => curried.apply(this, [...args, ...more]);
};
}