Last active
August 23, 2019 08:15
-
-
Save ottokruse/9d040e6d3b3e6b8f55072a152a1726c4 to your computer and use it in GitHub Desktop.
NodeJs crypto secure random choice from string or Array
This file contains 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
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