DEV Community

Cover image for Javascript Polyfill Reduce #2
chandra penugonda
chandra penugonda

Posted on • Edited on

Javascript Polyfill Reduce #2

Array.prototype.reduce() is a handy method to process arrays.

Example

[1, 2, 3].myReduce((prev, curr) => prev + curr, 0); // 6
[1, 2, 3].myReduce((prev, curr) => prev + curr, 4); // 10
Enter fullscreen mode Exit fullscreen mode

Note

  • Do not use native Array.prototype.reduce() in your code
  • your function is only tested against valid array (no array-like objects)

Solution

if (!Array.prototype.concat.myReduce) {
  Array.prototype.myReduce = function (callback, initialValue) {
    let index = 0;
    if (!initialValue) {
      index++;
      initialValue = this[0];
    }
    let acc = initialValue;
    for (let i = index; i < this.length; i++) {
      acc = callback(acc, this[i], i, this);
    }
    return acc;
  };
}

Enter fullscreen mode Exit fullscreen mode
  • We iterate through the array and call the callback function on each iteration, passing in the accumulator, current element, index and original array.
  • The initialValue is used as the first accumulator value if provided, otherwise the first element of the array is used.

Top comments (0)