JavaScriptEasy
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
- Throw a
TypeErrorifthisisnull/undefinedor the callback is not a function. - Convert
thiswithObject(this)so it works on array-likes (strings,arguments). - Read
lengthonce at the start (>>> 0to get a valid unsigned integer). Items appended during iteration are not visited. - Skip holes: only call the callback for indexes that exist (
i in O), and leave the same holes in the result. - Call the callback with
thisArgasthisand arguments(value, index, O). - Return a new array; never mutate the original.
- 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`);56 const O = Object(this);7 const len = O.length >>> 0; // read length once8 const result = new Array(len);910 for (let i = 0; i < len; i++) {11 if (i in O) result[i] = callback.call(thisArg, O[i], i, O); // skip holes12 }13 return result;14 },15 writable: true,16 configurable: true,17 enumerable: false,18});1920console.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"]2223// thisArg support24const multiplier = { factor: 10 };25console.log([1, 2].myMap(function (n) { return n * this.factor; }, multiplier)); // [10, 20]2627// Holes are preserved, like the native map28console.log([1, , 3].myMap((n) => n * 2)); // [2, <1 empty item>, 6]2930// Works on array-likes31console.log(Array.prototype.myMap.call("abc", (c) => c.toUpperCase())); // ["A", "B", "C"]3233// Validation34try {35 [1].myMap("not a function");36} catch (e) {37 console.log(e.name); // TypeError38}3940// Matches the native behaviour41const sample = [5, , 7];42console.log(JSON.stringify(sample.myMap((x) => x + 1)) === JSON.stringify(sample.map((x) => x + 1))); // true4344delete 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.