Skip to content

Instantly share code, notes, and snippets.

@oepn
Forked from aesnyder/random-weighted.coffee
Last active December 28, 2020 21:16
Show Gist options
  • Save oepn/33bc587bc09ce9895c43 to your computer and use it in GitHub Desktop.
Save oepn/33bc587bc09ce9895c43 to your computer and use it in GitHub Desktop.
Weighted random value in ES6
// 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