https://bigfrontend.dev/problem/implement-Array-prototype-map
Please implement your own Array.prototype.map().
[1, 2, 3].myMap((num) => num * 2);
// [2,4,6]
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.
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:
- 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. - The callback might alter the length of the calling array, resulting in an infinite loop.
- 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 are0, 2
, index1
is not in the array. Our function should ignore indices that are not present in the calling array.
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]
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:
-
Array.prototype.myMap = function (callback, thisArg) {...}
This line is extending the Array prototype with a new method calledmyMap
. This method takes two arguments: acallback
function and an optionalthisArg
object that will be used asthis
when executing the callback. -
const length = this.length;
: This line is storing the length of the array on whichmyMap
was called. This is done to avoid potential infinite loops if the array's length is changed during the execution ofmyMap
. -
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. -
The
for
loop: This loop iterates over each element in the original array. -
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). -
result[i] = callback.call(thisArg || this, this[i], i, this);
: This line is calling thecallback
function with the current element, its index, and the original array as arguments. The result is stored in the corresponding index of theresult
array.-
result[i]
: This is the assignment statement that assigns the return value of the callback function to thei
-th index of theresult
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 themyMap
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 ofthis
inside that function. In this case,callback.call(...)
is used to execute thecallback
function. -
thisArg || this
: This is the value that will be used as thethis
value inside thecallback
function. ThethisArg
argument is optional, so if it is not provided,this
(referring to the calling array) will be used as thethis
value. -
this[i]
: This is the current element of the array that is being processed by thecallback
function. It is passed as the first argument to thecallback
function. -
i
: This is the index of the current element in the array. It is passed as the second argument to thecallback
function. -
this
: This refers to the calling array itself. It is passed as the third ar gument to thecallback
function.[ 1, 2, 3, 4, 5 ]
-
-
return result;
: This line returns the new array after thefor
loop has finished executing.[ 2, 4, 6, 8, 10 ]