I want write reduce
by myself. But over the last 4 hours, I couldn't.
var a = [10, 21, 13, 56];
function add(a, b) { return a + b }
function foo(a, b) { return a.concat(b) }
Array.prototype.reduce2 = function () {
// I do not understand how to handle the function of the inlet
// I know that I should use arguments, but I don't know how many arguments there will be
var result = 0;
for(var i = 0; i < arguments.length; i++) {
result += arguments[i];
}
return result;
};
console.log(a.reduce(add), a.reduce2(add)) // 100 100
console.log(a.reduce(add, 10), a.reduce2(add, 10)) // 110 110
Yes, I know that this seems like a lot of topics, but I couldn't find answer. What am I missing, or doing wrong here?
The array in subject is not passed as argument, but is the context (this
).
You also need to distinguish between the presence or absence of the start value:
var a = [10, 21, 13, 56];
function add(a, b) { return a + b }
function foo(a, b) { return a.concat(b) }
Array.prototype.reduce2 = function (f, result) {
var i = 0;
if (arguments.length < 2) {
i = 1;
result = this[0];
}
for(; i < this.length; i++) {
result = f(result, this[i], i, this);
}
return result;
};
console.log(a.reduce(add), a.reduce2(add)) // 100 100
console.log(a.reduce(add, 10), a.reduce2(add, 10)) // 110 110
// extra test with foo:
console.log(a.reduce(foo, 'X'), a.reduce2(foo, 'X')) // X10211356 X10211356
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With