The polyfills for array methods such as map, filter and reduce methods can be created using array prototype.
- map:
The built-in Array.map method syntax will be helpful to write polyfill. The map method takes the callback function as an argument and that callback function can have below three arguments passed into it.
i. Current value
ii. Index of current value(optional)
iii. array(optional)
The syntax would like below,
let newArray = arr.map(callback(currentValue[, index, arr) {
})
Let's build our map polyfill based on the above syntax,
Array.prototype.myMap = function (cb) {
let newArr = [];
for (let i = 0; i < this.length; i++) {
newArr.push(cb(this[i], i, this));
}
return newArr;
};
const nums = [1, 2, 3, 4, 5];
const multiplyByTwo = nums.myMap((x) => x * 2);
console.log(multiplyByTwo);
In the above code, custom method name 'myMap' has been used to avoid conflicts with built-in method.
- filter:
Similar to map method,
Array.filter method takes callback function as an argument and the callback function can have three agurguments passed into it.
i. Current value
ii. Index of current value(optional)
iii. array(optional)
The syntax looks like below,
let newArray = arr.filter(callback(currentValue[, index, arr) {
})
Let's build our filter polyfill based on the above syntax,
Array.prototype.myFilter = function (cb) {
let newArr = [];
for (let i = 0; i < this.length; i++) {
if (cb(this[i], i, this)) {
newArr.push(this[i]);
}
}
return newArr;
};
const nums = [1, 2, 3, 4, 5, 6];
const evenNums = nums.myFilter((x) => x % 2);
console.log(evenNums);
- reduce:
The built-in Array.reduce method syntax will be helpful to write our own polyfill. The reduce method takes the callback function as first argument and the initial value as second argument.
The callback function can have four arguments passed into it.
i. Accumulator
ii. Current value
iii. Index of current value(optional)
iv. array(optional)
The syntax would like below,
arr.reduce(callback((acc, curr, i, arr) => {}), initValue);
Let's build our reduce polyfill based on the above syntax,
Array.prototype.myReduce = function(cb, initialValue) {
let accumulator = initialValue;
for(let i=0; i< this.length; i++) {
accumulator = accumulator ? cb(accumulator, this[i], i, this) : this[i];
}
return accumulator;
}
const nums = [1, 2, 3, 4, 5, 6];
const sum = nums.myReduce((acc, curr, i, arr) => {
return acc += curr
}, 0);
console.log(sum);