Skip to content

Instantly share code, notes, and snippets.

@ottokruse
Last active August 23, 2019 08:15
Show Gist options
  • Save ottokruse/9d040e6d3b3e6b8f55072a152a1726c4 to your computer and use it in GitHub Desktop.
Save ottokruse/9d040e6d3b3e6b8f55072a152a1726c4 to your computer and use it in GitHub Desktop.
NodeJs crypto secure random choice from string or Array
import { randomBytes } from 'crypto';
let bitsNeeded: number, bytesNeeded: number, chunks: number, tooBig: number, randomNumber: number, index: number;
export function randomChoiceFromIndexable(indexable: string | any[]) {
bitsNeeded = Math.log2(indexable.length);
bytesNeeded = Math.ceil(bitsNeeded / 8);
chunks = Math.floor(256 / indexable.length) || 1;
tooBig = indexable.length * chunks;
do {
randomNumber = randomBytes(bytesNeeded).readUIntBE(0, bytesNeeded);
} while (randomNumber >= tooBig);
index = randomNumber % indexable.length;
return indexable[index];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment