Skip to content

Instantly share code, notes, and snippets.

@Costava
Last active December 15, 2021 13:16
Show Gist options
  • Save Costava/c56863d9e8b1bb8e43ebbd81f7f571fd to your computer and use it in GitHub Desktop.
Save Costava/c56863d9e8b1bb8e43ebbd81f7f571fd to your computer and use it in GitHub Desktop.
// 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