Categories
interview

Array.map() Polyfill

Array.prototype.map = function(callback, context) {
  const ret = [];
  for (let index = 0; index < this.length; index++) {
    ret.push(callback.call(context, this[index], index, this));
  }
  return ret;
};

console.log([5, 4, 2].map((x, y) => {
  console.log(x, y);
  return 2 * x;
}));
/*
5, 0
4, 1
2, 2
[10, 8, 4]
*/

Demo