Just wrote a code for polyfill reduce() in JavaScript, thought I will share it will you all.
Array.prototype.myReduce = function(fn, initial) {
let values = this;
values.forEach(item => {
initial = initial !== undefined ? fn(initial, item) : item
})
return initial;
}
Using the above
var values = [2, 5, 5]
values.reduce((a, b) => a * b) // 50
values.myReduce((a, b) => a * b) // 50
I have dry tested it for multiple outputs. Do let me know if there can be any improvements.
Cheers!
Latest comments (7)
Array.prototype._reduce = function (callback, initial) {
}
in else part it should be this[i+1] not this[1]
I'm sorry but it doesn't make any sense to use forEach in a polyfill as a browser that doesn't support reduce is unlikely to support forEach as well. Same thing goes for the let keyword.
if (!Array.prototype.reduce) {
Array.prototype.reduce = function(cb, acc) {
var i = 0;
if (acc === void 0) {
acc = this[0];
i = 1;
}
for (; i < this.length; i++) {
var newAcc = cb(acc, this[i], i, this);
if (newAcc === undefined)
continue;
acc = newAcc;
}
return acc;
}
};
Would not work for undefined acc
It's almost same, Incase if anyone wants in simple form
Array.prototype.myReduce = function (callback, initialValue) {
let accumulator = initialValue === undefined ? undefined : initialValue;
for (let i = 0; i < this.length; i++) {
if (accumulator != undefined)
accumulator = callback(this[i], i, this)
else
accumulator = this[i];
}
return accumulator;
}
In other words:
let accumulator = initialValue;
thanks for posting the polyfill of the reducer. it will help me to crack interviews.