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);
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')
};
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)
Imagine you do this:
this would be the output:
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.