ES6+easy

Implement Array.prototype.map from scratch

Implement `Array.prototype.myMap` that behaves identically to the native `Array.prototype.map`. Handle sparse arrays and the `thisArg` parameter.

Asked at Apple

#arrays#prototype#higher-order functions

Answer

Array.prototype.myMap = function(callback, thisArg) {
  if (typeof callback !== 'function') {
    throw new TypeError(callback + ' is not a function')
  }

  const result = new Array(this.length)

  for (let i = 0; i < this.length; i++) {
    // Skip holes in sparse arrays (same as native map)
    if (Object.prototype.hasOwnProperty.call(this, i)) {
      result[i] = callback.call(thisArg, this[i], i, this)
    }
  }

  return result
}

// Test
;[1, 2, 3].myMap(x => x * 2)       // [2, 4, 6]
;[1, 2, 3].myMap((x, i) => i + x)  // [1, 3, 5]

// With thisArg
const multiplier = { factor: 3 }
;[1, 2, 3].myMap(function(x) {
  return x * this.factor
}, multiplier)   // [3, 6, 9]

Source: frontendinterviewhandbook.com — Apple

Practise more ES6+ questions →