Description

JavaScript provides the built-in Array.prototype.map() method that creates a new array by applying a callback function to each element.

To understand how array iteration and transformations work internally, you’ll implement your own version of map that behaves exactly like the native one.


Your Task

Implement a method Array.prototype.myMap that:

  • Accepts a callback function
  • Executes the callback for each element in the array
  • Returns a new array of the same length
  • Stores the callback’s return value at the same index
  • Does not mutate the original array
  • Behaves exactly like Array.prototype.map

Example

Input

Array.prototype.myMap = function (callback) {
// your implementation
};

const nums = [1, 2, 3];
const result = nums.myMap(n => n * 2);
console.log(result);

Output

[2, 4, 6]

More Examples

[1, 2, 3].myMap(n => n + 1);
// [2, 3, 4]

["a", "b"].myMap((ch, i) => ch + i);
// ["a0", "b1"]

[1, , 3].myMap(n => n * 2);
// [2, , 6]

Expected Behavior

  • Executes callback for each existing element
  • Preserves array length
  • Skips empty slots (sparse arrays)
  • Passes (element, index, array) correctly
  • Supports optional thisArg
  • Does not mutate the original array

Constraints

  • Do not use Array.prototype.map
  • Time complexity should be O(n)
  • Space complexity should be O(n)