Created
September 6, 2021 16:59
-
-
Save gchumillas/16dcdf52f48c92943c9da6ec16b772ce to your computer and use it in GitHub Desktop.
Pick a random item from a list
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
/** | |
* Picks a random item from a list. | |
* | |
* For example: | |
* | |
* pick(['a', 'b', 'c'], [0.7, 0.2]) | |
* // outputs 'a' with 70% chance | |
* // outputs 'b' with 20% chance | |
* // outputs 'c' with 10% chance (the rest) | |
* | |
* pick(['a', 'b', 'c']) | |
* // outputs 'a', 'b' or 'c' with the same probability | |
*/ | |
const pick = <T>(items: T[], rates: number[] = []) => { | |
if (!rates.length) { | |
return items[Math.floor(Math.random() * items.length)] | |
} | |
const p = Math.random() | |
let acc = 0 | |
for (const i in rates) { | |
const rate = rates[i] | |
if (p < acc + rate) { | |
return items[i] | |
} | |
acc += rate | |
} | |
return items[items.length - 1] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment