Created
October 11, 2024 17:52
-
-
Save ValchanOficial/471919bbf1fa841ec7b5d301485335a2 to your computer and use it in GitHub Desktop.
[Javascript] Generate a random number within a range using crypto.getRandomValues
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
// 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