Write a polyfill for Array.map in javascript

What is Aray.map?

Array.map accepts a callback function, executes the same over the original array and returns a new array.

 //Example: const arr = ar1.map(x => x*2)

What do we need a polyfill?

We need polyfills to support the old browsers for the new methods like Array.map etc. introduced in the latest ecmascript.

Polyfill for Array.map

Lets write a polyfill named myMap.

Note: "this" will contain the original array passed through the polyfill function.


function myMap(fun) {

  if (this === null || this === undefined) {

    console.log('myMap is iterating over an empty list.');

  }

  // validating function

  if (typeof fun !== 'function') {

    console.log('myMap is missing the callback function as a parameter.');

  }


  // get the original array

  var oArray = this;

  let output = [];

  console.log('original array: ', this, arguments);


  oArray.forEach((item) => {

    output.push(fun(item));

  });

  return output;

}

Array.prototype.myMap = myMap;


let arr = [1, 2, 3];

console.log('New array: ', arr.myMap(x => x*2)); // [2,4,6];



Read other such interview questions with solutions in my blog.

Write javascript polyfill for array.reduce



Comments

Popular posts from this blog

Abhijit Padhy

Find the longest substring in a given string.

Find the robot matching the given query having [top, right, bottom, left] index of the nearest walls in a 2D array.