Solution

To implement myMap, we iterate over the array and apply the callback function to each element. The return value of the callback becomes the corresponding element in the new array.

Algorithm:

  1. Validate that cb is a function (otherwise throw TypeError).
  2. Create an empty result array.
  3. Iterate from 0 to this.length - 1.
  4. For each index i, compute cb(this[i], i, this) and store it in result[i].
  5. Return result.
Array.prototype.myMap = function (cb) {
  if (typeof cb !== "function") {
    throw new TypeError("myMap callback must be a function");
  }

  const result = [];
  for (let i = 0; i < this.length; i++) {
    result[i] = cb(this[i], i, this);
  }
  return result;
};

// Usage
const arr = [1, 2, 3, 4, 5];
const res = arr.myMap((item) => {
  return item * 2;
});

console.log(res); // [2, 4, 6, 8, 10]

Complexity:

  • Time complexity: O(N)
  • Space complexity: O(N)