https://bigfrontend.dev/problem/implement-Array-prototype-map
Please implement your own Array.prototype.map().
[1, 2, 3].myMap((num) => num * 2);
// [2,4,6]Write a prototype method for Array that returns a new array populated with the result of calling a provided function on every element in the calling array.
Create an empty array to store the result. Iterate through every items in the calling array. At each item, call the provided callback and pass the item, its index and the calling array as arguments to the callback; store the return value in the result array.
🙋♀️🙋♂️ In the initial attempt, I didn't handle the following cases:
- Besides the callback function, our function can also take in a second argument, the optional
thisArg, when it is provided, the callback function should be executed with the provided context. - The callback might alter the length of the calling array, resulting in an infinite loop.
- The calling array is a sparse array. A sparse array is an array in which indices are not contiguous. For instance,
[1, 3]is a sparse array and the indices are0, 2, index1is not in the array. Our function should ignore indices that are not present in the calling array.
Array.prototype.myMap = function (callback, thisArg) {
// Store the length of the original array to avoid potential infinity loop
// when the length of the calling array is altered on the fly.
const length = this.length;
// Initialize the resulting array to be the same size as the calling array.
const result = new Array(length);
for (let i = 0; i < length; i++) {
// Ensure index is in the array. myMap should ignore
// indices that are not in the array.
if (i in this) {
// Execute the callback with proper context and store its return value in the
// result array.
result[i] = callback.call(thisArg || this, this[i], i, this);
}
}
return result;
};