Created
March 17, 2021 15:59
-
-
Save neodigm/f082a0f024e676536e5370f4c4e570b4 to your computer and use it in GitHub Desktop.
unbiased dice roll in browser
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
| function getCryptoRange(min, max) { | |
| const range = max - min + 1 | |
| const mBits = Math.ceil(Math.log2(range)) | |
| const mBytes = Math.ceil(mBits / 8) | |
| const nAllowed = Math.floor((256 ** mBytes) / range) * range | |
| const arBytes = new Uint8Array(mBytes) | |
| let value | |
| do { | |
| crypto.getRandomValues(arBytes) | |
| value = arBytes.reduce((acc, x, n) => acc + x * 256 ** n, 0) | |
| } while (value >= nAllowed) | |
| return min + value % range | |
| } | |
| console.log( getCryptoRange( 1, 6 )) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment