Skip to content

Instantly share code, notes, and snippets.

@ronenteva
Created August 23, 2019 06:48
Show Gist options
  • Save ronenteva/c66abbd8be7b8fc87c36e5f893444347 to your computer and use it in GitHub Desktop.
Save ronenteva/c66abbd8be7b8fc87c36e5f893444347 to your computer and use it in GitHub Desktop.
const _ = require('lodash');
const experiments = [
{
id: 'A',
weight: 0.2,
}, {
id: 'B',
weight: 0.4,
}, {
id: 'C',
weight: 0.4,
}
];
const weightedSample = arr => {
const total = _.sumBy(arr, 'weight');
const rand = _.random(total, true);
let i = 0;
let step = arr[0].weight;
while (rand > step) {
step += arr[i + 1].weight;
i++;
}
return arr[i]
};
console.log(weightedSample(experiments));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment