You are tasked with implementing a polyfill for the Array.map() method in JavaScript. The goal is to replicate the functionality of the native Array.map() method, which creates a new array by applying a provided function to each element of the array.
Write a function named map that takes a callback function as its argument and returns a new array with the results of applying the callback function to each element of the original array.
Your polyfill should support the following:
Accept an optional second argument, which will be used as the value of this when executing the callback function.
Handle the three parameters that the callback function receives: currentValue, index, and the array itself.
Here's a detailed explanation of the provided solution code:
1- The map function is defined as an exportable function. It takes two parameters:
arr: The original array on which the map operation will be performed.
callbackFn: The callback function that will be applied to each element of the array.
2- Inside the function, a new array named output is initialized to store the results of applying the callback function to each element of the original array.
3- The forEach method is used to iterate over each element of the arr array. For each element, the callback function (callbackFn) is called with three arguments:
element: The current element of the array being processed.
index: The index of the current element within the array.
this: The value of this is not explicitly specified here, so it will default to undefined or the global object, depending on whether the function is called in strict mode.
4- Inside the callback function, the callbackFn is invoked with three arguments:
element: The current element of the original array.
index: The index of the current element within the original array.
this: The value of this is passed as the third argument to the callback function. This allows the callback function - to access the specified context if provided.
5- The result of each invocation of the callback function is pushed into the output array.
6- Finally, the map function returns the output array, which contains the results of applying the callback function to each element of the original array.
This implementation mimics the behavior of the native Array.map() method by creating a new array with the results of applying the provided callback function to each element of the original array, while also supporting the optional this context and the three parameters (currentValue, index, and the array itself`) passed to the callback function.