I have been learning about spread arguments and I found it rather surprising that when using: cur.func.call(null, ...cur.arg, acc), args)
that if you have an empty array no argument is passed to add()
.
Is it possible to reproduce this without using the ...
seen in this line of code cur.func.call(null, ...cur.arg, acc), args)
class Lazy {
constructor() {
this.builtUpFuncs = [];
}
add(...newArgs) {
console.info(newArgs)
this.builtUpFuncs.push({
func: newArgs[0],
arg: typeof newArgs[1] === "undefined" ? [] : [newArgs[1]],
});
return this;
}
evaluate(target) {
return target.map((args) =>
this.builtUpFuncs.reduce((acc, cur) =>
cur.func.call(null, ...cur.arg, acc), args)
);
}
}
const lazyClass = new Lazy();
const returnValue =
lazyClass
.add(function timesTwo(a) { return a * 2; })
.add(function plus(a, b) { return a + b; }, 1)
.evaluate([1, 2, 3]);
console.info(returnValue);