Skip to content

Instantly share code, notes, and snippets.

@insign
Created January 11, 2018 22:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save insign/ab3f92676323fc4a3910fbd040151609 to your computer and use it in GitHub Desktop.
Save insign/ab3f92676323fc4a3910fbd040151609 to your computer and use it in GitHub Desktop.
Faster alternative for Array.reduce()
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