From e7fa0ea5253a89460c2021a53dbebaa4ff4ce38f Mon Sep 17 00:00:00 2001 From: Dan Hayden Date: Wed, 26 Jul 2017 15:52:15 +0100 Subject: [PATCH] fix: use Number.isFinite polyfill to fix IE11 compatibility --- package.json | 2 +- src/pick-by-weight.js | 16 ++++++++++++++++ src/react-simple-experiment.js | 4 ++-- 3 files changed, 19 insertions(+), 3 deletions(-) create mode 100644 src/pick-by-weight.js diff --git a/package.json b/package.json index 6c86fac..83ed71e 100644 --- a/package.json +++ b/package.json @@ -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": { diff --git a/src/pick-by-weight.js b/src/pick-by-weight.js new file mode 100644 index 0000000..a74d4e7 --- /dev/null +++ b/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] + } + } +} diff --git a/src/react-simple-experiment.js b/src/react-simple-experiment.js index fcddb76..192f734 100644 --- a/src/react-simple-experiment.js +++ b/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'}) @@ -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) }