JSFiddle - React, Tailwind, and code Playground

by Udi Talias

HTML

<button onclick="run()">
run
</button>

JavaScript

function getRandomValue(highestInclusive) {
  return Math.ceil(Math.random() * highestInclusive);
}

window.run = function run() {

  const AB_TESTS = [{
      value: 20,
      params: {
        adLookupTimeout: 0,
      }
    },
    {
      value: 30,
      params: {
        adLookupTimeout: 60 * 1000,

      }
    },
    {
      value: 50,
      params: {
        adLookupTimeout: 60 * 1000,

      }
    }
  ];

  AB_TESTS.sort((a, b) => a.value - b.value);

  const randomValue = getRandomValue(100);
  let variant;

  let aggregation = 0;
  for (let i = 0, len = AB_TESTS.length; i < len; i++) {
    if (aggregation + AB_TESTS[i].value >= randomValue) {
      variant = AB_TESTS[i];
      break;
    }
    aggregation += AB_TESTS[i].value;
  }

  console.log(randomValue, variant)
}