Last active
December 15, 2021 13:16
-
-
Save Costava/c56863d9e8b1bb8e43ebbd81f7f571fd to your computer and use it in GitHub Desktop.
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
// Return random string of given length. | |
// Use Math.random function. | |
function mathRandomString(length) { | |
const set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; | |
let result = ""; | |
for (let i = 0; i < length; i += 1) { | |
result += set[Math.floor(Math.random() * set.length)]; | |
} | |
return result; | |
} | |
// Return random string of given length. | |
// Use crypto.getRandomValues function. | |
function cryptoRandomString(length) { | |
const set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; | |
let randVals = new Uint32Array(length); | |
crypto.getRandomValues(randVals); | |
let result = ""; | |
for (let i = 0; i < length; i += 1) { | |
result += set[randVals[i] % set.length]; | |
} | |
return result; | |
} | |
// Print some. | |
for (let i = 0; i < 4; i += 1) { | |
console.log(mathRandomString(32)); | |
} | |
console.log(); | |
for (let i = 0; i < 8; i += 1) { | |
console.log(cryptoRandomString(32)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment