Created
August 23, 2019 06:48
-
-
Save ronenteva/c66abbd8be7b8fc87c36e5f893444347 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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