DEV Community 👩‍💻👨‍💻

Cherag Verma
Cherag Verma

Posted on

Polyfill for Array.reduce() Javascript

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!

Top comments (6)

Collapse
melvdouc profile image
Melvin DOUCET • Edited on

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;
}
};

Collapse
ad99526 profile image
Abhishek Dubey

Would not work for undefined acc

Collapse
srinivaskandukuri profile image
~#S*K#~

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;
}

Collapse
melvdouc profile image
Melvin DOUCET • Edited on

let accumulator = initialValue === undefined ? undefined : initialValue;

In other words:
let accumulator = initialValue;

Collapse
surajpandey186 profile image
Suraj Bhushan Pandey

Array.prototype._reduce = function (callback, initial) {

if (initial) {
    previous = initial;

   for (let i = 0; i < this.length; ++ i) {
      previous = callback(previous, this[i], i, this)
   }

} else {
    previous = this[0]
    for (let i = 1; i < this.length; ++ i) {
        previous = callback(previous, this[1], i, this)
    }
}
return previous
Enter fullscreen mode Exit fullscreen mode

}

Collapse
sagar profile image
Sagar

thanks for posting the polyfill of the reducer. it will help me to crack interviews.

🤔 Did you know?

 
🌚 Dark mode is available in Settings.