Last active
March 4, 2021 01:02
-
-
Save v19i/411abe971c9c7fe9c79fdc5d4e86a9cf to your computer and use it in GitHub Desktop.
Generate Random String
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
function generateRandomString(length) { | |
var id = ""; | |
for (let i = 0; i < length; i++) { | |
const r = getRandomNumber(); | |
if (r < 0.5) { | |
id += getNumberWithinRange(r, 0, 9); | |
} else { | |
id += String.fromCharCode(getNumberWithinRange(r, 97, 122)); | |
} | |
} | |
return id; | |
} | |
function getRandomNumber() { | |
if (window.crypto && window.crypto.getRandomValues) { | |
// Divide a random UInt32 by the maximum value (2^32 -1) to get a result between 0 and 1 | |
return window.crypto.getRandomValues(new Uint32Array(1))[0] / 4294967295; | |
} | |
return Math.random(); | |
} | |
function getNumberWithinRange(r, min, max) { | |
return Math.floor(r * (max - min + 1)) + min; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment