Skip to content

Instantly share code, notes, and snippets.

@codingoutloud
Created August 30, 2020 17:21
Show Gist options
  • Save codingoutloud/7bde33cc6c5f8a75582a8d3916708a98 to your computer and use it in GitHub Desktop.
Save codingoutloud/7bde33cc6c5f8a75582a8d3916708a98 to your computer and use it in GitHub Desktop.
JavaScript functions for choosing a random integer between 0 and some max value. There are two variants: one where max is supplied, and one where an array is supplied.
// Return a random integer in [0..max] (inclusive, so 0 and max are valid values).
// Assumes (but does not validate) that max is a non-negative integer less than Number.MAX_SAFE_INTEGER.
// Does not use a Cryptographically Secure Pseudo-Random Number Generator (CSPRNG).
function getRandomInt(max) {
return Math.floor(Math.random() * (max + 1));
// How it works:
// Math.random() → returns a floating point number at least zero but less than one: [0..1)
// Math.random() * (max+1) → returns a floating point number at least 0 but less than (max+1): [0..max+1)
// floor(Math.random() * (max+1)) → returns an integer at least 0 but could be as high as max: [0..max]
// Example of how it works:
// For max=5, the range of possible return values is 0..5
// floor(0 * (5+1)) = floor(0) = 0 → lowest possible Math.random() return value is 0
// floor(0.00001 * (5+1)) = floor(0.00006) = 0 → low end of Math.random() return values (0.00001)
// floor(0.99999 * (5+1)) = floor(5.99994) = 5 → high end of Math.random() return values (0.99999)
}
// Return a random array index from provided array: [0..(array.length-1)] (inclusive, so 0 and array.length-1 are valid values).
// Assumes (but does not validate) that array contains at least one element.
// Does not use a Cryptographically Secure Pseudo-Random Number Generator (CSPRNG).
function getRandomIndex(array) {
// syntactic sugar for when goal is to choose randomly within an existing array
return getRandomInt(array.length-1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment