react-alpha-beta
Version:
Simple declarative A/B testing component for React.
51 lines (41 loc) • 1.81 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _stringify = require('babel-runtime/core-js/json/stringify');
var _stringify2 = _interopRequireDefault(_stringify);
exports.isInCohort = isInCohort;
var _constants = require('./constants');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Given an `experimentParams` object with `id` and `testCohortSize`,
* it determines whether the user is in the control group or the experimental
* group.
* It maintains a global registery of experiments in an object. This consists of
* a mapping of experiment ids to random numbers, that can be used to determine
* if the user is in the experimental group or not.
* @params {string} experimentParams.testId - Experiment id.
* @params {number} experimentParams.testCohortSize - Number between 0 and 1
* that indicates the portion of the users that need to be in the experimental
* group.
*/
function isInCohort(experimentParams) {
var experimentId = experimentParams.id;
// Retrieve from storage or create experiment registery
var alphaBetaMap = void 0;
try {
var jsonStr = global.localStorage.getItem(_constants.localStorageKey);
alphaBetaMap = jsonStr && JSON.parse(jsonStr) || {};
} catch (err) {
alphaBetaMap = {};
}
// Get and set a random number (<1) in the registery of the experimentId
if (!(experimentId in alphaBetaMap)) {
alphaBetaMap[experimentId] = Math.random();
var _jsonStr = (0, _stringify2.default)(alphaBetaMap);
global.localStorage.setItem(_constants.localStorageKey, _jsonStr);
}
// Return if this user is in the experiment,
// if they are below the treshold they are in the cohort
return alphaBetaMap[experimentId] < experimentParams.testCohortSize;
}