Before we start writing polyfill for map, first let's talk about map function in general.
map function in JavaScript is a higher order function which accept a callback function as an argument and returns a new array in response.
the map function executes the callback function with currentElement, index and array for every element in array.
// nums.map((currentElement, index, array) => { // })
const nums = [1, 2, 3, 4, 5]
const ans = nums.map((el) => {
return el * 10
})
console.log(ans) // [10, 20, 30, 40, 50]
First we create a customMap function which accepts a callback and optional contextArgs. and assign it to Array.prototype.
Array.prototype.customMap = function(cb, contextArgs){
// ...
}
inside our customMap function first we add some checks for whether the callback is a function or not and the array is not null.
Array.prototype.customMap = function(cb, contextArgs){
if(this == null) throw new TypeError("array is null or undefined")
if(typeof cb != 'function') throw new TypeError(`${cb} is not a function`)
}
After that we use a for loop to loop through the array and call the callback function. and store the result to a new result array.
Array.prototype.customMap = function(cb, contextArgs){
if(this == null) throw new TypeError("array is null or undefined")
if(typeof cb != 'function') throw new TypeError(`${cb} is not a function`)
const result = []
for(let i = 0; i < this.length; i++){
if(i in this){
result[i] = cb.call(contextArgs, this[i], i, this)
}
}
return result
}
Join Aditya on Peerlist!
Join amazing folks like Aditya and thousands of other people in tech.
Create ProfileJoin with Aditya’s personal invite link.
0
5
0