Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
unbiased dice roll in browser
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