Polyfill of Array.reduce()
The reduce() method of Array instances executes a user-supplied “reducer” callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
The first time that the callback is run there is no “return value of the previous calculation”. If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).
function myReduce(callback, initialValue) {
if (!this) throw new Error("Array is not defined");
const array = this;
const n = array.length;
if (!n) {
if (initialValue || initialValue === 0) return initialValue;
else throw new Error("Reduce of empty array with no initial value");
}
let index = 0;
let accumulator;
if (initialValue || initialValue === 0) {
accumulator = initialValue;
} else {
accumulator = array[index];
index += 1;
}
while (index < n) {
accumulator = callback(accumulator, array[index], index, array);
index++;
}
return accumulator;
};
Array.prototype.mapPolyfill = myReduce;
const arr = [1, 2, 3];
const ans = arr.mapPolyfill((prev, curr) => prev + curr, 1);
console.log(ans);
// Output:
7