Introduction
Before creating polyfills for the map, reduce, and filter method, let's first take a look at what they are used for.
Map Method
The map method creates a new array by transforming the original array according to our needs. The below code shows how the method works
const arr = [1, 2, 3, 4, 5];
const twiceArr = arr.map((value, index, array) => {
return value * 2;
})
console.log(twiceArr) // [ 2, 4, 6, 8, 10 ]
Map methods take a callback function and the callback function has three parameters- value: current value, index: current index, and **array **: the whole array. Below is the code for the polyfill of the map method.
Polyfill for map method
const array = [1, 2, 3, 4];
// Polyfill method
Array.prototype.myMap = function (cb) {
let temp = [];
for (let i = 0; i < this.length; i++) {
temp.push(cb(this[i], i, this));
}
return temp;
}
const twiceArr = array.myMap((item, i, arr) => {
return item * 2;
});
console.log(twiceArr); // [ 2, 4, 6, 8, 10 ]
Filter Method
The filter method returns a new array with elements satisfying the condition we have passed in the callback function.
const arr = [1, 2, 3, 4, 5];
const evenArr = arr.filter((value, index, array) => {
if (value % 2 == 0) {
return value;
}
})
console.log(evenArr) // [ 2, 4 ]
Filter methods take a callback function and the callback function has three parameters- value: current value, index: current index, and **array **: the whole array. Below is the code for the polyfill of the filter method.
Polyfill for filter method
const array = [1, 2, 3, 4];
Array.prototype.myFilter = function (cb) {
let temp = [];
for (let i = 0; i < this.length; i++) {
if (cb(this[i], i, this)) {
temp.push(this[i]);
}
}
return temp;
}
const filteredArray = array.myFilter((item, index, arr) => {
if (item % 2 == 0) {
return item;
}
});
console.log(filteredArray); // [ 2 , 4 ]
Reduce method
Reduce method is used when we want a single value as an output, it can be used to find the total sum of all elements in an array.
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((acc, curr, index, array) => {
return acc + curr;
}, 0);
console.log(sum) // 15
Reduce methods take a callback function and an initial value for the accumulator. The callback function has four parameters - acc: accumulator, curr current value, index: current index, array: whole array. Below is the code for the polyfill of the reduce method.
Polyfill for reduce method
const arr = [1,2,3,4,5];
Array.prototype.myReduce = function (cb, initialValue) {
var accumulator = initialValue;
for (let i = 0; i < this.length; i++) {
accumulator = accumulator ? cb(accumulator, this[i], i, this) : this[i];
}
return accumulator;
};
const sum = arr.myReduce((acc, curr) => {
return acc + curr;
}, 0);
console.log(sum); // 15
If an initial value is not provided then the accumulator takes the value of the first index and the callback function is called for the following elements leaving the index 0.