Solution
To implement myMap, we iterate over the array and apply the callback function to each element. The return value of the callback becomes the corresponding element in the new array.
Algorithm:
- Validate that
cbis a function (otherwise throwTypeError). - Create an empty
resultarray. - Iterate from
0tothis.length - 1. - For each index
i, computecb(this[i], i, this)and store it inresult[i]. - Return
result.
Array.prototype.myMap = function (cb) {
if (typeof cb !== "function") {
throw new TypeError("myMap callback must be a function");
}
const result = [];
for (let i = 0; i < this.length; i++) {
result[i] = cb(this[i], i, this);
}
return result;
};
// Usage
const arr = [1, 2, 3, 4, 5];
const res = arr.myMap((item) => {
return item * 2;
});
console.log(res); // [2, 4, 6, 8, 10]
Complexity:
- Time complexity:
O(N) - Space complexity:
O(N)