Skip to content

Instantly share code, notes, and snippets.

@neodigm
Created March 17, 2021 15:59
Show Gist options
  • Select an option

  • Save neodigm/f082a0f024e676536e5370f4c4e570b4 to your computer and use it in GitHub Desktop.

Select an option

Save neodigm/f082a0f024e676536e5370f4c4e570b4 to your computer and use it in GitHub Desktop.
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