Skip to content

Instantly share code, notes, and snippets.

@ValchanOficial
Created October 11, 2024 17:52
Show Gist options
  • Save ValchanOficial/471919bbf1fa841ec7b5d301485335a2 to your computer and use it in GitHub Desktop.
Save ValchanOficial/471919bbf1fa841ec7b5d301485335a2 to your computer and use it in GitHub Desktop.
[Javascript] Generate a random number within a range using crypto.getRandomValues
// https://stackoverflow.com/a/65440696
function random(min, max) {
const range = max - min + 1
const bytes_needed = Math.ceil(Math.log2(range) / 8)
const cutoff = Math.floor((256 ** bytes_needed) / range) * range
const bytes = new Uint8Array(bytes_needed)
let value
do {
crypto.getRandomValues(bytes)
value = bytes.reduce((acc, x, n) => acc + x * 256 ** n, 0)
} while (value >= cutoff)
return min + value % range
}
console.log(random(0, 100))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment