is number of arguments
// that callback can accept before
// it has to be called
const arity = callback.length;
const storage = Array.isArray(this) ? this : [];
if (arity === 0) {
return callback;
}
const acceptArity = (...args) => {
storage.push(...args);
if (storage.length < arity) {
return ArityWithCallback.call(storage, callback);
}
// calculation
const result = callback(...storage.slice(0, arity));
// storage cleanup
storage.length = 0;
return result;
};
return acceptArity;
};
const func = (a, b, c, d, e) => a + b + c + d + e;
const hof = ArityWithCallback(func);
console.log(hof(1, 2, 3, 4, 5)); // 15
console.log(hof(2, 3, 4)(5, 6)); // 20
console.log(hof(3, 4)(5, 6)(7)); // 25
console.log(hof(4, 5)(6)(7, 8)); // 30
console.log(hof(5)(6)(7)(8)(9)); // 35
https://gist.github.com/wentout/02bd3fd6188c014e4947e36321a816d8
Обсуждают сегодня