Created
January 11, 2018 22:50
-
-
Save insign/ab3f92676323fc4a3910fbd040151609 to your computer and use it in GitHub Desktop.
Faster alternative for Array.reduce()
This file contains hidden or 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.aggregate = function (fn, initialValue) { | |
let current | |
const length = this.length | |
if (length == 0 && initialValue) return initialValue | |
else if (length == 0) throw 'Reduce of empty array with no initial value' | |
else if (length == 1 && initialValue) return fn(initialValue, this[0]) | |
else if (length == 1) return this[0] | |
else if (initialValue) current = fn(initialValue, this[0]) | |
else current = this[0] | |
for (let i = 1; i < length; ++i) { | |
current = fn(current, this[i]) | |
} | |
return current | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment