Skip to content
Onsite

Implement Array.prototype.map

EasyP1Coding

Implement myMap, a polyfill for Array.prototype.map.

myMap is a regular function that is called with the array as its this value: myMap.call(arr, callback, thisArg). It returns a new array where element i is callback.call(thisArg, arr[i], i, arr).

Rules that match the real method:

  • The original array is not changed.
  • Holes in a sparse array are skipped, and the result keeps the same holes.
  • If callback is not a function, throw a TypeError.

Example 1

Input
myMap.call([1, 2, 3], x => x * 2)
Output
[2, 4, 6]

Example 2

Input
myMap.call(['a', 'b'], (x, i) => x + i)
Output
['a0', 'b1']

Constraints

  • 0 <= array length <= 10^5
  • Do not call the built-in Array.prototype.map.

Hints

Run checks the 3 visible tests, Submit all 7.