There was an excellent post from trincot in Oct 2016 regarding construction of a piping function using the reduce method (link to posting), and I'm trying to understand the code in detail.
ES6 Version
function piper(...fs) {
return (...args) => fs.reduce((args,f) => [f.apply(this,args)],args)[0];
}
Specifically:
1. Instead of [f.apply(this.args)], f(...args) also works, but f(args) doesn't work. Why doesn't f(args) work?
2. Regarding the second parameter in the internal (anonymous) "reduce" function, why is args even necessary? . . ., i.e., why doesn't the following code work?
function piper(...fs) {
return (...args) => fs.reduce((args,f) => [f.apply(this,args)])[0];
}
B. Alternatively, why can't we just use [] as a parameter instead of args?
function piper(...fs) {
return (...args) => fs.reduce((args,f) => [f.apply(this,args)],[])[0];
}
ES5 Version
function piper(/* functions */) {
var fs = [].slice.apply(arguments);
return function (/* arguments */) {
return fs.reduce(function (args,f) {
return [f.apply(this,args)];
}.bind(this), [].slice.apply(arguments))[0];
}.bind(this);
}
Questions:
1. In the internal (anonymous) reduce function, why do we need the second parameter [].slice.apply(arguments)? i.e., why doesn't [] work in in its place?
2. Alternatively, why can't we just leave out that parameter entirely?
Many thanks in advance for helping me understand these issues at a deeper level.