Skip to content

Instantly share code, notes, and snippets.

@insign insign/aggregate.js
Created Jan 11, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.