forked from pushtell/react-ab-test
-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathcalculateActiveVariant.jsx
More file actions
77 lines (69 loc) · 2.52 KB
/
calculateActiveVariant.jsx
File metadata and controls
77 lines (69 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import crc32 from 'fbjs/lib/crc32';
import emitter from './emitter';
import store from './store';
import storeCookie from './storeCookie';
const calculateVariant = (experimentName, userIdentifier) => {
/*
Choosing a weighted variant:
For C, A, B with weights 2, 4, 8
variants = A, B, C
weights = 4, 8, 2
weightSum = 14
weightedIndex = 9
AAAABBBBBBBBCC
========^
Select B
*/
// Sorted array of the variant names, example: ["A", "B", "C"]
const variants = emitter.getSortedVariants(experimentName);
// Array of the variant weights, also sorted by variant name. For example, if
// variant C had weight 2, variant A had weight 4, and variant B had weight 8
// return [4, 8, 2] to correspond with ["A", "B", "C"]
const weights = emitter.getSortedVariantWeights(experimentName);
// Sum the weights
const weightSum = weights.reduce((a, b) => {
return a + b;
}, 0);
// A random number between 0 and weightSum
let weightedIndex =
typeof userIdentifier === 'string'
? Math.abs(crc32(userIdentifier) % weightSum)
: Math.floor(Math.random() * weightSum);
// Iterate through the sorted weights, and deduct each from the weightedIndex.
// If weightedIndex drops < 0, select the variant. If weightedIndex does not
// drop < 0, default to the last variant in the array that is initially assigned.
let selectedVariant = variants[variants.length - 1];
for (let index = 0; index < weights.length; index++) {
weightedIndex -= weights[index];
if (weightedIndex < 0) {
selectedVariant = variants[index];
break;
}
}
emitter.setActiveVariant(experimentName, selectedVariant);
return selectedVariant;
};
export default (experimentName, userIdentifier, defaultVariantName) => {
if (typeof userIdentifier === 'string') {
return calculateVariant(experimentName, userIdentifier);
}
const activeValue = emitter.getActiveVariant(experimentName);
if (typeof activeValue === 'string') {
return activeValue;
}
let storedValue;
if (emitter.withCookie()) {
storedValue = storeCookie().getCookie('PUSHTELL_COOKIE-' + experimentName);
} else {
storedValue = store.getItem('PUSHTELL-' + experimentName);
}
if (typeof storedValue === 'string') {
emitter.setActiveVariant(experimentName, storedValue, true);
return storedValue;
}
if (typeof defaultVariantName === 'string') {
emitter.setActiveVariant(experimentName, defaultVariantName);
return defaultVariantName;
}
return calculateVariant(experimentName);
};