Skip to content

Latest commit

 

History

History
58 lines (40 loc) · 2.15 KB

File metadata and controls

58 lines (40 loc) · 2.15 KB

151. implement Array.prototype.map()

Problem

https://bigfrontend.dev/problem/implement-Array-prototype-map

Problem Description

Please implement your own Array.prototype.map().

[1, 2, 3].myMap((num) => num * 2);
// [2,4,6]

Understanding the problem

Write a prototype method for Array that returns a new array populated with the result of calling a provided function on every element in the calling array.

Approach

Create an empty array to store the result. Iterate through every items in the calling array. At each item, call the provided callback and pass the item, its index and the calling array as arguments to the callback; store the return value in the result array.

🙋‍♀️🙋‍♂️ In the initial attempt, I didn't handle the following cases:

  1. Besides the callback function, our function can also take in a second argument, the optional thisArg, when it is provided, the callback function should be executed with the provided context.
  2. The callback might alter the length of the calling array, resulting in an infinite loop.
  3. The calling array is a sparse array. A sparse array is an array in which indices are not contiguous. For instance, [1, 3] is a sparse array and the indices are 0, 2, index 1 is not in the array. Our function should ignore indices that are not present in the calling array.

Solution

Array.prototype.myMap = function (callback, thisArg) {
  // Store the length of the original array to avoid potential infinity loop
  // when the length of the calling array is altered on the fly.
  const length = this.length;
  // Initialize the resulting array to be the same size as the calling array.
  const result = new Array(length);

  for (let i = 0; i < length; i++) {
    // Ensure index is in the array. myMap should ignore
    // indices that are not in the array.
    if (i in this) {
      // Execute the callback with proper context and store its return value in the
      // result array.
      result[i] = callback.call(thisArg || this, this[i], i, this);
    }
  }

  return result;
};