Created
June 1, 2022 02:16
-
-
Save ZeroDragon/79a3c4c65f1f536cd17f8993818468e4 to your computer and use it in GitHub Desktop.
True Random Generator
This file contains hidden or 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
/** | |
* 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