I want to write a recursive version of reduce function.
Array.prototype.reduce2 =
function reduce(fn, initial) {
var head = this[0];
var tail = this.slice(1);
var result = fn(initial, head, 0, tail);
return reduce(tail, fn, result);
}
var a = [1, 2, 3, 4];
function add(a, b) { return a + b } ;
function mul(a, b) { return a * b } ;
function foo(a, b) { return a.concat(b) };
console.log(a.reduce(add), a.reduce2(add)); // 10 10
console.log(a.reduce(add, 10), a.reduce2(add, 10)) ; // 20 20
console.log(a.reduce(add, undefined), a.reduce2(add, undefined)); // NaN NaN
console.log(a.reduce(mul), a.reduce2(mul)); // 24 24
console.log(a.reduce(foo, ''), a.reduce2(foo, '')); // 1234 123
The result was:
10 [Function: add]
20 [Function: add]
NaN [Function: add]
24 [Function: mul]
1234 function foo(a, b) { return a.concat(b) }
Yes, I know that this seems like a lot of topics, but I couldn't find answer.
fnwith 4 parameters when it only accepts 2? Your recursion has no stopping clause. You're callingreducewith 3 parameters when it accepts 2.