- Published on
Polyfill for map function in JavaScript
- Authors
- Name
- Mrinmay Mukherjee
- @devmrin
Naive Implementation
myMap.js
Array.prototype.myMap = function (callbackFn, thisArg) {
let array = this;
let returnedArray = [];
for (let i = 0; i < array.length; i++) {
let callbackArguments = [array[i], i, array];
if (thisArg) {
returnedArray.push(callbackFn.call(thisArg, ...callbackArguments));
} else {
returnedArray.push(callbackFn(...callbackArguments));
}
}
return returnedArray;
};
Syntax to fulfill
// Arrow function
myMap((element) => {
/* ... */
})
myMap((element, index) => {
/* ... */
})
myMap((element, index, array) => {
/* ... */
})
// Callback function
myMap(callbackFn)
myMap(callbackFn, thisArg)
// Inline callback function
myMap(function (element) {
/* ... */
})
myMap(function (element, index) {
/* ... */
})
myMap(function (element, index, array) {
/* ... */
})
myMap(function (element, index, array) {
/* ... */
}, thisArg)