Skip to content

Instantly share code, notes, and snippets.

@shekhardtu
Created September 3, 2019 19:25
Show Gist options
  • Save shekhardtu/80425b082e99fb2aa6270d436e8bbeaa to your computer and use it in GitHub Desktop.
Save shekhardtu/80425b082e99fb2aa6270d436e8bbeaa to your computer and use it in GitHub Desktop.
polyfill of reduce method in javascript
Array.prototype.myReduce = function() {
var arr = this;
var len = arr.length;
var fn = arguments[0];
var i = 0;
var acc = arguments[1];
if (arguments.length < 2) {
i = 1;
acc = arr[0];
}
for (; i < len; i++) {
acc = fn(acc, arr[i], i, arr)
}
return acc;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8];
var myReduce = arr.myReduce((prev,item)=>prev + item);
var reduce = arr.reduce((prev,item)=>prev + item);
console.log(myReduce);
// 36
console.log(reduce);
// 36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment