UNPKG

1.5 kBJavaScriptView Raw
1function selectExperimentVariant(config, selectedVariant) {
2 // If no experiment is configured, do nothing.
3 if (!config) {
4 return null;
5 }
6 // A valid cookie has the format xxxxxxxx.n where the first part is the experiment id and the second part is the variant index
7 const parts = (selectedVariant || '').split('.');
8 if (parts.length === 2) {
9 const [experiment, variant] = parts;
10 // Make sure the cookie refers to the currently configured experiment
11 if (experiment === config.experimentId) {
12 // Make sure that the variant index is withing the amount of variants we have configured
13 if (parseInt(variant, 10) < config.variantWeights.length) {
14 return selectedVariant;
15 }
16 }
17 }
18 const totalWeights = config.variantWeights.reduce((sum, cur) => sum + cur, 0);
19 const absoluteWeights = config.variantWeights.map(weight => weight / totalWeights);
20 // We either have no previous cookie, or an invalid one, so let's select a variant and set up the cookie
21 const randomValue = Math.random();
22 const variantCount = absoluteWeights.length;
23 let i = 0, sum = 0;
24 for (; i < variantCount; i++) {
25 if (randomValue < sum + absoluteWeights[i]) {
26 break;
27 }
28 else {
29 sum += absoluteWeights[i];
30 }
31 }
32 return `${config.experimentId}.${i}`;
33}
34export default selectExperimentVariant;
35//# sourceMappingURL=selectExperimentVariant.js.map
\No newline at end of file