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)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay