Curry a function accepting any number of args per call
Strict currying passes exactly one argument per call: f(a)(b)(c). In real code that gets tedious, so most libraries let each call pass as many arguments as you like, and run the function as soon as it has received enough of them.
Implement curry(fn). It returns a curried version of fn that collects arguments across calls until it has at least fn.length of them, then calls fn.
curry(fn) // => curried
fn.length, return a new curried function that remembers them. fn is not called.fn.length or more, call fn with all collected arguments, including any extras, and return its result.fn.length is 0, the first call runs fn right away.undefined and null count as arguments.this value of the call that completes the arguments is passed to fn.Remember that fn.length counts only parameters before the first one with a default value or a rest parameter: (a, b = 2) => {} has length 1.
const volume = curry((width, height, depth) => width * height * depth);
volume(2)(3)(4); // => 24
volume(2, 3)(4); // => 24
volume(2)(3, 4); // => 24
volume()(2)()(3, 4); // => 24 (empty calls change nothing)
const base = volume(10);
base(1)(1); // => 10
base(2, 5); // => 100 (base is unchanged by the call above)
const label = curry(function (prefix, id) {
return [prefix, id, ...[...arguments].slice(2)].join('-');
});
label('sku')(42, 'red', 'xl'); // => 'sku-42-red-xl' (extras are passed through)
const now = curry(() => 'ran');
now(); // => 'ran'
const priced = curry(function (amount, qty) {
return `${this.currency}${amount * qty}`;
});
const shop = { currency: '€', total: priced(5) };
shop.total(3); // => '€15'