Skip to content

Instantly share code, notes, and snippets.

@thomd
Created March 10, 2016 13:34
Show Gist options
  • Save thomd/c0cf72e5a1d7b0a8d263 to your computer and use it in GitHub Desktop.
Save thomd/c0cf72e5a1d7b0a8d263 to your computer and use it in GitHub Desktop.
Array.prototype.reducePolyfill()
import expect from 'expect'
let items = [{price: 19.9}, {price: 59}, {price: 120}, {price: 29.9}]
// the reducer
const add = function add(sum, item) {
return sum + item.price
}
expect(items.reduce(add, 0)).toEqual(228.8)
Array.prototype.reducePolyfill = (function() {
let value
return function reducer(fn, startValue) {
if(startValue != undefined) {
value = startValue
}
let curr = this.shift()
if(this.length > 0) {
reducer.call(this, fn)
}
value = fn(value, curr)
return value
}
})()
expect(items.reducePolyfill(add, 0)).toEqual(228.8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment