Created
March 10, 2016 13:34
-
-
Save thomd/c0cf72e5a1d7b0a8d263 to your computer and use it in GitHub Desktop.
Array.prototype.reducePolyfill()
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
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