-
-
Save oepn/33bc587bc09ce9895c43 to your computer and use it in GitHub Desktop.
Weighted random value in ES6
This file contains hidden or 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
// Defined first due to TDZ | |
let weighted = (...weightMap) => weightMap | |
.map(({0: value, 1: weight}) => new Array(weight).fill(value)) | |
.reduce((acc, current) => [...acc, ...current]); | |
let random = (array) => array[Math.floor(Math.random() * array.length)]; | |
// You can generate a weighted array | |
weighted([true, 1], [false, 2]); // [true, false, false] | |
weighted([true, 1], [false, 3]); // [true, false, false, false] | |
// Then random picks one randomly | |
// The following will return true or false with a 1:3 ratio | |
random(weighted([true, 1], [false, 3])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment