Skip to content

Instantly share code, notes, and snippets.

@jlengstorf
Last active August 7, 2024 21:51
Show Gist options
  • Save jlengstorf/43b26eae49e9af6db6b0abb16bf84e0f to your computer and use it in GitHub Desktop.
Save jlengstorf/43b26eae49e9af6db6b0abb16bf84e0f to your computer and use it in GitHub Desktop.
As close to actually random selection as I can figure out with JavaScript.
// get the entries into an array
const entries = ['[email protected]', '[email protected]', '[email protected]', '[email protected]'];
function getRandomEntry(entry_array) {
const NUMBER_OF_ENTRIES = entry_array.length;
const UINT16_MAX_VALUE = 65_535;
/**
* `crypto.getRandomValues()` generates a cryptographically secure random value
*
* @see https://mdn.io/crypto.getRandomValues
*/
const randomNumber = crypto.getRandomValues(new Uint16Array(1)).at(0);
// clamp range to one of the available entry indices
const winnerIndex = Math.floor(randomNumber / ((UINT16_MAX_VALUE + 1) / NUMBER_OF_ENTRIES));
const winner = entry_array.at(winnerIndex);
return winner;
}
console.log({ winner: getRandomEntry(entries) });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment