Last active
October 22, 2017 16:55
-
-
Save aesnyder/c8898a9002e50ba65373 to your computer and use it in GitHub Desktop.
Weighted random value in underscore or lodash
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
## First you can generate a weighted array | |
weighted 1: true, 2: false # [true, false, false] | |
weighted 1: true, 3: false # [true, false, false, false] | |
## Then random picks one randomly | |
## The following will return true or false with a 1:3 ratio | |
random weighted 1: true, 3: false | |
# here's the magic, you need underscore or lodash | |
weighted = (weightMap) -> | |
_ weightMap | |
.map (val, weight) -> _.times weight, -> val | |
.flatten() | |
.value() | |
random = (arr) -> _.shuffle(arr)[0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can replace
_.shuffle(arr)[0]
by_.pick(arr)
I believe!