Q37 [Coding]: Write a custom polyfill for Array.prototype.map().
Array.prototype.myMap = function(callback, thisArg) {
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
const result = [];
for (let i = 0; i < this.length; i++) {
if (i in this) { // Handles sparse arrays
result[i] = callback.call(thisArg, this[i], i, this);
}
}
return result;
};
Key Takeaways
- Iterates over input array elements and constructs a new mapped array.
- Handles sparse array indices using
i in thischecks.
Knowledge Check
Does Array.prototype.map() mutate the original calling array instance?