Skip to content

Latest commit

 

History

History
100 lines (62 loc) · 5.21 KB

151.implement-Array-prototype-map.md

File metadata and controls

100 lines (62 loc) · 5.21 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;
};

// Usage 
const arr = [1, 2, 3, 4, 5];
const mappedArr = arr.myMap((el) => el * 2);
console.log(mappedArr); // [2, 4, 6, 8, 10]

Explanation

This JavaScript code is a custom implementation of the Array.prototype.map()function, which is a built-in method in JavaScript that creates a new array with the results of calling a provided function on every element in the calling array.

Here's a breakdown of the code:

  1. Array.prototype.myMap = function (callback, thisArg) {...} This line is extending the Array prototype with a new method called myMap. This method takes two arguments: a callback function and an optional thisArg object that will be used as this when executing the callback.

  2. const length = this.length;: This line is storing the length of the array on which myMap was called. This is done to avoid potential infinite loops if the array's length is changed during the execution of myMap.

  3. const result = new Array(length);: This line is initializing a new array with the same length as the original array. This will be the array that gets returned at the end.

  4. The for loop: This loop iterates over each element in the original array.

  5. if (i in this) {...}: This line checks if the current index exists in the original array. This is done because in JavaScript, arrays can have "holes" (i.e., indices that have never been assigned a value).

  6. result[i] = callback.call(thisArg || this, this[i], i, this);: This line is calling the callback function with the current element, its index, and the original array as arguments. The result is stored in the corresponding index of the resultarray.

    • result[i]: This is the assignment statement that assigns the return value of the callback function to the i-th index of the result array. It ensures that the return value is stored at the correct position in the resulting array.

    • callback: This is the function that is passed as an argument to the myMap function. It is the function that will be executed on each element of the array. (el) => el * 2

    • call(): call() is a method available on JavaScript functions. It allows you to invoke a function and specify the value of this inside that function. In this case, callback.call(...) is used to execute the callback function.

    • thisArg || this: This is the value that will be used as the this value inside the callback function. The thisArg argument is optional, so if it is not provided, this (referring to the calling array) will be used as the this value.

    • this[i]: This is the current element of the array that is being processed by the callback function. It is passed as the first argument to the callback function.

    • i: This is the index of the current element in the array. It is passed as the second argument to the callback function.

    • this: This refers to the calling array itself. It is passed as the third ar gument to the callback function.[ 1, 2, 3, 4, 5 ]

  7. return result;: This line returns the new array after the for loop has finished executing. [ 2, 4, 6, 8, 10 ]