Polyfills for map, filter and reduce | JavaScript Interview

Polyfills for map, filter and reduce | JavaScript Interview

If you are preparing for JavaScript Interview, Frontend Interview or Backend Interview where most of the stuff is done using JavaScript, then there is a high possibility that you will be asked to implement your version(called Polyfill) of an inbuilt JS function like map, filter, etc.

What exactly is Polyfill and why is it asked?

A polyfill is a piece of computer code written to implement a feature in a browser that does not yet support it. It could be because of the older version of the browser you are using, or because the new version of the browser does not have that feature.

Coming to why is it asked, creating a polyfill demonstrates that you have a strong understanding of JavaScript's core concepts, including functions, prototypes, closures, and other language features. It also shows your ability to work with the language at an advanced level.

map function

The map function is used to transform each element of an array by applying a provided callback function. It creates a new array containing the results of applying the callback to each element of the original array.

// Syntax of map function
// Array.map((currVal, index, arr)=>{})
const arr=[1,2,3,4,5];
const sqArr=arr.map((item)=>item*item);
const multByIndex=arr.map((item,index)=>item*index);

In the above example, we can see that the map function takes a callbackFn. The function is executed for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments:

  1. currVal: The current element being processed in the array.

  2. index: The index of the current element being processed in the array.

  3. arr: The array map was called upon.

  4. thisArg [Optional]: A value to use as this when executing callbackFn.

Now let's write the polyfill for the map:

const arr=[1,2,3,4,5];

Array.prototype.myMap=function(cb){
  let temp=[];
  for(let i=0;i<this.length;i++){
      temp.push(cb(this[i],i,this)); 
  }
  return temp;
}

const newArr=arr.myMap((item,index)=>item*index);
const sqArr=arr.myMap((item)=>item*item);
console.log(newArr);
console.log(sqArr);

Code Breakdown:

  1. An array arr is created with values [1, 2, 3, 4, 5].

  2. The myMap method is added to the Array prototype. This method takes a callback function cb as its argument.

  3. Inside the myMap method:

    • A temporary array temp is created to store the transformed values.

    • A loop goes through each element of the array.

    • The callback function cb is applied to each element, along with its index and the original array. The result is added to the temp array.

    • The temp array is returned.

  4. The results are logged into the console.

filter function

The filter function is used to create a new array containing only the elements that pass a certain condition specified by the provided callback function.

// Syntax of filter function
// array.filter((currentValue, index, arr)=>{});
const words = ['Hello', 'World', '!', 'How', 'Are', 'You'];
const result = words.filter((word) => word.length > 6);
console.log(result);

In the above example, we can see that the filter function takes a callbackFn. This function is executed for each element in the array. It should return a truthy value to keep the element in the resulting array, and a falsy value otherwise. The function is called with the following arguments:

  1. currVal: The current element being processed in the array.

  2. index: The index of the current element being processed in the array.

  3. arr: The array filter was called upon.

  4. thisArg [Optional]: A value to use as this when executing callbackFn.

Now let's write the polyfill for the filter function:

const words = ['Hello', 'World', '!', 'How', 'Are', 'You'];

Array.prototype.myFilter=function(cb){
  let temp=[];
  for(let i=0;i<this.length;i++){
   if(cb(this[i],i,this)){
     temp.push(this[i]);
   } 
  }
  return temp;
}

const result = words.myFilter((word) => word!=="!");
console.log(result);

Code Breakdown:

  1. An array of words is defined by several words.

  2. The myFilter method is added to the Array prototype. This method takes a callback function cb as its argument.

  3. Inside the myFilter method:

    • A temporary array temp is created to store the filtered values.

    • A loop iterates over each element of the array.

    • The callback function cb is applied to each element, and if the result is true, the element is added to the temp array.

    • The temp array containing filtered values is returned.

  4. The myFilter method is used with a callback that checks if a word is not equal to "!".

  5. The filtered result is logged into the console.

reduce function

The reduce function is used to "reduce" an array to a single value by applying a callback function to each element, accumulating a result along the way.

// Syntax of reduce function
// array.reduce((total, currValue, currIndex, arr)=>{}, initialValue)
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);
console.log(sum);

In the above example, we can see that the reduce function takes a callbackFn. This function is executed for each element in the array. Its return value becomes the value of the accumulator parameter on the next invocation of callbackFn. For the last invocation, the return value becomes the return value of reduce(). The function is called with the following arguments:

  1. currValue: The value of the current element. On the first call, the value of array[0] if an initialValue was specified, otherwise the value of array[1].

  2. accumulator: The value resulting from the previous call to callbackFn. On the first call, initialValue if specified, otherwise the value of array[0].

  3. index: The index position of currentValue in the array. On the first call, 0 if initialValue was specified, otherwise 1.

  4. arr: The array reduce was called upon.

  5. initialValue [Optional]: A value to which accumulator is initialized the first time the callback is called. If initialValue is specified, callbackFn starts executing with the first value in the array as currentValue. If initialValue is not specified, accumulator is initialized to the first value in the array, and callbackFn starts executing with the second value in the array as currentValue.

Now let's write the polyfill for the reduce function:

const numbers = [1, 2, 3, 4, 5];

Array.prototype.myReduce=function(cb,initialValue){
    let accumulator=initialValue;
    for(let i=0;i<this.length;i++){
        accumulator=accumulator?cb(accumulator,this[i],i,this):this[i];
    }
    return accumulator;
}
const sum = numbers.myReduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);
console.log(sum);

Code Breakdown:

  1. An array numbers are defined: [1, 2, 3, 4, 5].

  2. A custom myReduce function is added to the Array prototype:

    • It takes two arguments: cb (callback function) and initialValue.

    • An accumulator is initialized with the value of initialValue.

    • A loop iterates over the array elements.

    • For each element, the cb function is called with arguments accumulator, this[i] (current element), i (index), and this (original array). The result is assigned to the accumulator.

    • The accumulator is returned after the loop.

  3. Using myReduce to calculate the sum:

    • The myReduce function is used on the numbers array.

    • The callback function (accumulator, currentValue) => accumulator + currentValue adds the current value to the accumulator.

    • An initial value of 0 is provided for the accumulator.

  4. The sum is logged to the console.

We have written polyfill for map, filter, and reduce. 👏

In the upcoming blog, we will be learning about Promises and difference between all of its methods.

Thanks for reading🙂

Did you find this article valuable?

Support Suvesh's Blog by becoming a sponsor. Any amount is appreciated!