Create a polyfill for map()

A map polyfill creates a new array of the same length, calls the callback with (element, index, array) and the optional thisArg for each existing element, and stores the results; it must validate the callback and skip holes in sparse arrays.

Spec details to get right

  1. Throw a TypeError if this is null/undefined or the callback is not a function.
  2. Convert this with Object(this) so it works on array-likes (strings, arguments).
  3. Read length once at the start (>>> 0 to get a valid unsigned integer). Items appended during iteration are not visited.
  4. Skip holes: only call the callback for indexes that exist (i in O), and leave the same holes in the result.
  5. Call the callback with thisArg as this and arguments (value, index, O).
  6. Return a new array; never mutate the original.
  7. Define it as non-enumerable with Object.defineProperty, and only if it is missing (in a real polyfill).

What interviewers look for

Correct this handling (use a regular function, not an arrow), argument order, not mutating the input, and awareness of sparse arrays. Mentioning Object.defineProperty and feature detection shows production thinking.

Complexity

O(n) time, O(n) space for the result.

Code example

js
1Object.defineProperty(Array.prototype, "myMap", {
2 value: function myMap(callback, thisArg) {
3 if (this == null) throw new TypeError("Array.prototype.myMap called on null or undefined");
4 if (typeof callback !== "function") throw new TypeError(`${callback} is not a function`);
5
6 const O = Object(this);
7 const len = O.length >>> 0; // read length once
8 const result = new Array(len);
9
10 for (let i = 0; i < len; i++) {
11 if (i in O) result[i] = callback.call(thisArg, O[i], i, O); // skip holes
12 }
13 return result;
14 },
15 writable: true,
16 configurable: true,
17 enumerable: false,
18});
19
20console.log([1, 2, 3].myMap((n) => n * 2)); // [2, 4, 6]
21console.log([1, 2, 3].myMap((n, i, arr) => `${i}/${arr.length}`)); // ["0/3", "1/3", "2/3"]
22
23// thisArg support
24const multiplier = { factor: 10 };
25console.log([1, 2].myMap(function (n) { return n * this.factor; }, multiplier)); // [10, 20]
26
27// Holes are preserved, like the native map
28console.log([1, , 3].myMap((n) => n * 2)); // [2, <1 empty item>, 6]
29
30// Works on array-likes
31console.log(Array.prototype.myMap.call("abc", (c) => c.toUpperCase())); // ["A", "B", "C"]
32
33// Validation
34try {
35 [1].myMap("not a function");
36} catch (e) {
37 console.log(e.name); // TypeError
38}
39
40// Matches the native behaviour
41const sample = [5, , 7];
42console.log(JSON.stringify(sample.myMap((x) => x + 1)) === JSON.stringify(sample.map((x) => x + 1))); // true
43
44delete Array.prototype.myMap; // clean up

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app