Polyfill for Array methods: map(), filter() and reduce() š
Hey! You may have been asked this question in an interview or maybe not. Whatever the case is, it doesnāt hurt to always know more. So here Iāll be sharing how to create polyfill for the map, filter, and reduce array methods.
Letās Code !
Pollyfill for Array.map()
Letās first see how Array.map() works from its syntax:
let newArray = arr.map(callback(currentValue[, index[, array]]) {
// return element for newArray, after executing something
});
So, the original Array.map function takes a callback function as an argument and that callback function can have three arguments passed into it :
a. current value
b. index of the current value [optional]
c. array [optional]
Based on that, letās build our own map function :
Array.prototype.myMap = function(callbackFn) {
var arr = [];
for (var i = 0; i < this.length; i++) {
/* call the callback function for every value of this array and push the returned value into our resulting array
*/
arr.push(callbackFn(this[i], i, this));
}
return arr;
}
Pollyfill for Array.filter()
Letās first see how Array.filter() works from its syntax:
let newArray = arr.filter(callback(currentValue[, index[, array]]) {
// return element for newArray, if true
});
So, the original Array.filter function takes a callback function as an argument and that callback function can have three arguments passed into it :
a. current value
b. index of the current value [optional]
c. array [optional]
Based on that, letās build our own filter function :
Array.prototype.myFilter = function(callbackFn) {
var arr = [];
for (var i = 0; i < this.length; i++) {
if (callbackFn.call(this, this[i], i, this)) {
arr.push(this[i]);
}
}
return arr;
}
Pollyfill for Array.reduce()
Letās first see how Array.reduce() works from its syntax:
arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])
So, the original Array.reduce function takes two arguement :
1. A callback function as an argument and that callback function can have four arguments passed into it :
a. accumulator
b. current value
c. index of the current value [optional]
d. array [optional]
2. An initial value.
Based on that, letās build our own reduce function :
Array.prototype.myReduce= function(callbackFn, initialValue) {
var accumulator = initialValue;for (var i = 0; i < this.length; i++) {
if (accumulator !== undefined) {
accumulator = callbackFn.call(undefined, accumulator, this[i], i, this);
} else {
accumulator = this[i];
}
}
return accumulator;
}
If you like this post, please click the applause icon and follow me here for more!
Follow the Polyfill series below: