DEV Community

Shubham Jindal
Shubham Jindal

Posted on

Polyfill of Reduce

Hi, friends
I am writing the polyfill of Reduce...
So those readers are not aware of what is Array.reduce please take a look at the MDN site.
Here is the Link :
Array.reduce()

So First I am sharing my whole code of custom Reduce function
then we will discuss the code Line by Line

Array.prototype.myReduce = function(callback, initalValue){

 // Start Handling of errors
 if(this==null || this==undefined) {
   return('The Array you passed is null or undefined')
 };

 if(!callback || typeof callback !== 'function') {
   return('callback not exist or not a function')
 };

 if(!this.length){
   if(arguments.length<2){
     return('Array is empty && intialValue is not given');
   }else{
     return(initalValue);
   }
 }
 // End of handling of errors

 if(this.length){
 var k = 0;
 var acc;
 if(arguments.length<2){
   acc = this[0];
   k++;
 }else if(arguments.length==2){
   acc = initalValue
 }

  while(k<this.length){
    acc = callback(acc, this[k]);
    k++;
  }
  return(acc);
 }
}

const sum = (a,b)=>{return a*b};
let result = [1,3].myReduce(sum, 5);
console.log(result);
result = [1,3,5].myReduce(sum, 4);
console.log(result);
result = [].myReduce(sum, 4);
console.log(result);
result = [1,2].myReduce(sum);
console.log(result);
Enter fullscreen mode Exit fullscreen mode

Okay Now I am explaining the code

The first Condition is

if(this==null || this==undefined) {
   return('The Array you passed is null or undefined')
 };
Enter fullscreen mode Exit fullscreen mode

Here this referring to the Array you passed... means if the Array you passes is null or undefined output should be an error...
for more use case you can check out the original Reduce function on the MDN site

Top comments (1)

Collapse
 
shadowtime2000 profile image
shadowtime2000

Imagine you do this:

for (const i in myArray) {
console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

this would be the output:

someElem1
someElem2
myReduce
Enter fullscreen mode Exit fullscreen mode

This is another basic snippet of code that has been shared around the internet a bit and you also didn't explain how it works.