Skip to content

Instantly share code, notes, and snippets.

@ZeroDragon
Created June 1, 2022 02:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZeroDragon/79a3c4c65f1f536cd17f8993818468e4 to your computer and use it in GitHub Desktop.
Save ZeroDragon/79a3c4c65f1f536cd17f8993818468e4 to your computer and use it in GitHub Desktop.
True Random Generator
/**
* This small gist is based on https://github.com/nastyox/Rando.js
* The idea of this gist is to have a compatible node and browser script that can replace Math.random()
* using crypto libraries built-in in node and browser and without the extra baggage for automatic object
* array o string behaviours
* it fallbacks to Math.random()
**/
const rando = () => {
try {
let crypto
try {
crypto = require('crypto').randomFillSync
} catch (_) {
crypto = (window.crypto || window.msCrypto).getRandomValues
}
let cryptoRandoms
const cryptoRandomSlices = []
let cryptoRandom
while ((cryptoRandom = '.' + cryptoRandomSlices.join('')).length < 30) {
cryptoRandoms = crypto(new Uint32Array(5))
for (let i = 0; i < cryptoRandoms.length; i++) {
const cryptoRandomSlice = cryptoRandoms[i] < 4000000000 ? cryptoRandoms[i].toString().slice(1) : ''
if (cryptoRandomSlice.length > 0) cryptoRandomSlices[cryptoRandomSlices.length] = cryptoRandomSlice
}
}
return Number(cryptoRandom)
} catch (_) {
return Math.random()
}
}
/**
* USAGE: rando()
**/
// console.log(rando())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment