Categories
interview

Implement Array.prototype.map()

Array.prototype.map = function(mapper, thisArg) {
  const arr = [];

  for (const [key] of Object.entries(this)) {
    arr[key] = mapper.call(thisArg, this[key], key >>> 0, this);
  }

  return arr;
}

const arr = [];
arr[0] = 0;
arr[2] = 2;
arr[3] = 3;
console.log(arr); // [0, undefined, 2, 3]
console.log(arr.map(x => 2 * x)); // [0, undefined, 4, 6]

Demo