Curry a variadic function that runs on an empty call
Classic currying waits until a function has received fn.length arguments. That does not work for variadic functions such as Math.max or a sum(...nums) helper, whose length is 0 or misleading. A common alternative is to keep collecting arguments until the caller signals the end with an empty call: add(1)(2, 3)(4)().
Implement curryVariadic(fn). It returns a curried version of fn that collects arguments across calls and runs fn when called with no arguments.
curryVariadic(fn) // => curried
fn is not called.fn with all collected arguments (as separate arguments, in order) and returns its result.f(1, 2)(3)() and f(1)(2)(3)() both call fn(1, 2, 3).fn again.undefined and null passed explicitly are arguments. Only a call with arguments.length === 0 runs fn.this value of the final, empty call is passed to fn.curryVariadic(fn)() right away calls fn() with no arguments.const sum = (...nums) => nums.reduce((total, n) => total + n, 0);
const add = curryVariadic(sum);
add(1)(2, 3)(4)(); // => 10
add(5, 5)(); // => 10
add(); // => 0
const path = curryVariadic((...parts) => parts.join('/'));
const api = path('api', 'v2');
api('users')(); // => 'api/v2/users'
api('orders', 42)(); // => 'api/v2/orders/42'
api(); // => 'api/v2' (api is unchanged by the calls above)
const greet = curryVariadic(function (...names) {
return `${this.greeting}, ${names.join(' and ')}`;
});
const team = { greeting: 'Hello', welcome: greet('Ana', 'Raj') };
team.welcome(); // => 'Hello, Ana and Raj'