Skip to content

Commit

Permalink
fix: use Number.isFinite polyfill to fix IE11 compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
danhayden committed Jul 26, 2017
1 parent 99df2a7 commit e7fa0ea
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -39,8 +39,8 @@
"react": "^15.0.0-0"
},
"dependencies": {
"is-finite": "1.0.2",
"localforage": "1.5.0",
"pick-one-by-weight": "1.0.2",
"prop-types": "15.5.10"
},
"devDependencies": {
Expand Down
16 changes: 16 additions & 0 deletions src/pick-by-weight.js
@@ -0,0 +1,16 @@
import isFinite from 'is-finite'

export default function pickOneByWeight (anObj) {
let _keys = Object.keys(anObj)
const sum = _keys.reduce((p, c) => p + anObj[c], 0)
if (!isFinite(sum)) {
throw new Error('All values in object must be a numeric value')
}
let choose = ~~(Math.random() * sum)
for (let i = 0, count = 0; i < _keys.length; i++) {
count += anObj[_keys[i]]
if (count > choose) {
return _keys[i]
}
}
}
4 changes: 2 additions & 2 deletions src/react-simple-experiment.js
@@ -1,6 +1,6 @@
import React from 'react'
import PropTypes from 'prop-types'
import pickOneByWeight from 'pick-one-by-weight'
import pickByWeight from './pick-by-weight'
import Storage from './storage'

const storage = Storage({name: 'react-simple-experiment'})
Expand Down Expand Up @@ -31,7 +31,7 @@ export class Experiment extends React.Component {

storage.getItem(storageName).then(variant => {
if (!variant || !variantNames.includes(variant) || data[variant] < 1) {
variant = pickOneByWeight(data)
variant = pickByWeight(data)
storage.setItem(storageName, variant)
}

Expand Down

0 comments on commit e7fa0ea

Please sign in to comment.