Creating Polyfills for map, filter, and reduce Array Methods
In this blog post, we embark on a journey to explore the inner workings of these fundamental array methods and learn how to craft polyfills for them. So, let’s roll up our sleeves and dive into the world of JavaScript polyfills, unlocking the true potential of our favorite programming language.
Pollyfill for Array.map()
array.map((currentValue, index, array) => { // function body });
As we can see, Array.map takes a callback as an argument, and that callback can have 3 arguments – currentValue, index(optional) and array(optional).
Now Let’ write our polyfill :
Array.prototype.myMap = function(callbackFun) {
let newArray = [];
for (let i = 0; i < this.length; i++) {
newArray.push(callbackFun(this[i], i, this));
}
return newArray;
};
let arr = [10, 20, 30];
let newArr = arr.myMap((x) => {
return x * 2;
});
console.log(newArr);
// output : [ 20, 40, 60 ]
Pollyfill for Array.filter()
Array.filter() syntax:
array.filter((currentValue, index, array) => { // function body });
As we can see, Array.filter takes a callback as an argument, and that callback can have 3 arguments – currentValue, index(optional) and array(optional)
Now, let’s write our polyfill:
Array.prototype.myFilter = function(callbackFun) {
let newArray = [];
for (let i = 0; i < this.length; i++) {
if (callbackFun(this[i], i, this)) {
newArray.push(this[i]);
}
}
return newArray;
};
let arr = [10, 15, 30];
let newArr = arr.myFilter((x) => {
return x % 10 == 0;
});
console.log(newArr);
//Output: [10 , 30]
Pollyfill for Array.reduce()
Array.reduce() syntax:
array.reduce((accumulator, currentValue, index, array) => { // function body }, initialValue);
As we can see, Array.reduce takes 2 arguments, first as a callback, and second an initialValue. Now again that callback can have 4 arguments – accumulator, currentValue, index(optional) and array(optional).
Now, let’s write our polyfill:
Array.prototype.myReduce = function(callbackFun, initialValue) {
let acc = initialValue;
for (let i = 0; i < this.length; i++) {
acc = acc ? callbackFun(acc, this[i], i, this) : this[i];
}
return acc;
};
let arr = [10, 15, 30];
let newArr = arr.myReduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(newArr);
// output : 55
Conclusion
Diving into the world of polyfills for essential array methods like map
, filter
, and reduce
provides invaluable insights into JavaScript’s underlying mechanics and empowers developers to write more robust and cross-compatible code. By understanding how these methods work under the hood and creating polyfills to support older environments, developers can ensure that their applications remain accessible and functional across a wide range of browsers and platforms.