DEV Community

Cover image for Javascript Polyfill Array.map #3
chandra penugonda
chandra penugonda

Posted on • Updated on

Javascript Polyfill Array.map #3

This problem was asked by Amazon.

What is a polyfill ?

In web development, a polyfill is code that implements a feature on web browsers that do not natively support the feature

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

Example

[1,2,3].myMap(num => num * 2) // [2,4,6]
[1, 4, 9, 16].myMap(num => num * 2) // [2, 8, 18, 32]

Enter fullscreen mode Exit fullscreen mode

Note: Do not use native Array.prototype.map() in your code

Solution

if (!Array.prototype.customMap) {
  Array.prototype.customMap = function (cb, args) {
    const len = this.length;
    const result = new Array(len);
    if (typeof cb !== "function") {
      throw new TypeError(cb + " is not a function");
    }
    for (let i = 0; i < len; i++) {
      result[i] = cb.call(args, this[i], i, this);
    }
    return result;
  };
}
Enter fullscreen mode Exit fullscreen mode
  • This polyfill defines the .map() method on Array.prototype if it does not already exist natively. It implements the .map() functionality by:
  • Checking if .map() exists, and if not, defining it
  • Checking the this value is defined
  • Getting the length of the array
  • Checking if the callback is a function
  • Handling an optional thisArg
  • Creating a new array to store the results
  • Iterating through the array using a for loop
  • Calling the callback on each element and storing the result in the new array
  • Returning the new array

Top comments (0)