call(back)

Implement Array.prototype.map

Write Array.prototype.myMap(cb, thisArg) so it matches the built-in map. The grader disables the native map, filter, reduce and concat while your code runs.

Rules

  • Call cb.call(thisArg, value, index, array) for each element. A callback that isn't a function throws TypeError.
  • Return a new array of the same length that keeps holes, never calling back for them.
  • Define the method with function, not an arrow, so this is the array.
[1, 2, 3].myMap((v) => v * 2)        // [2, 4, 6]
[1, , 3].myMap((v) => v * 2)         // [2, <hole>, 6]

Tests write a hole as "<hole>"; the grader turns it into a real empty slot and back. Callbacks are named in each test's input and supplied by the grader.

Hints

Hint 1

i in this tells a hole from a stored undefined.

Hint 2

Pre-size the output with new Array(len) and write only the indices you visit, so holes stay holes.

Asked at