Sequence NODE_158
Medium

Implement Custom Array.map

JavaScript
Technical Specification

Implement a custom map function called myMap that works similarly to Array.prototype.map.

Input/Output Samples
Input:[1,2,3].myMap(x => x * 2)
Output:[2,4,6]
Optimal Logic Path
Array.prototype.myMap = function (callback) {
  const result = [];
  for (let i = 0; i < this.length; i++) {
    if (Object.prototype.hasOwnProperty.call(this, i)) {
      result.push(callback(this[i], i, this));
    }
  }
  return result;
};
Architectural Deep-Dive
We attach myMap to Array.prototype so it can be called on any array while iterating and building a new array from callback results.