Implement Array.prototype.map
Implement a custom Array.prototype.myMap method that works similarly to Array.prototype.map.
myMap creates a new array by applying a callback function to every element of the original array.
Requirements
- Add a method named
myMaptoArray.prototype. myMap(callback)must:- Return a new array (do not mutate the original array).
- Call
callbackfor each index from0toarray.length - 1. - Call
callbackwith arguments:(currentValue, index, array). - Produce a result array where each entry is the return value of
callbackat the same index.
- If
callbackis not a function, throw aTypeError.
Constraints
- Do not use the built-in
Array.prototype.map.
Example
const numbers = [1, 2, 3, 4, 5];
const squaredNums = numbers.myMap((number) => {
return number * number;
});
console.log(squaredNums); // Output: [1, 4, 9, 16, 25]