Created
September 3, 2019 19:25
-
-
Save shekhardtu/80425b082e99fb2aa6270d436e8bbeaa to your computer and use it in GitHub Desktop.
polyfill of reduce method in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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