1 | function selectExperimentVariant(config, selectedVariant) {
|
2 |
|
3 | if (!config) {
|
4 | return null;
|
5 | }
|
6 |
|
7 | const parts = (selectedVariant || '').split('.');
|
8 | if (parts.length === 2) {
|
9 | const [experiment, variant] = parts;
|
10 |
|
11 | if (experiment === config.experimentId) {
|
12 |
|
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 |
|
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 | }
|
34 | export default selectExperimentVariant;
|
35 |
|
\ | No newline at end of file |