Last active
January 13, 2022 14:12
-
-
Save mitchallen/cc6f96e30f7eccf10763fe8bf309eb6e to your computer and use it in GitHub Desktop.
Selected an item from a weighted choice list
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
| // Author: Mitch Allen | |
| // File: weighted-choice.js | |
| export function weightedChoice(source) { | |
| let rnd = Math.random(); | |
| let lower = 0.00; | |
| for (let choice in source) { | |
| let weight = source[choice]; | |
| let upper = lower + weight; | |
| if (rnd >= lower && rnd < upper) { | |
| return choice; | |
| } | |
| lower = upper; | |
| } | |
| // Never reached 100% and random | |
| // number is out of bounds | |
| return undefined; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment