Skip to content

Instantly share code, notes, and snippets.

@kavunshiva
Last active November 13, 2018 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kavunshiva/4840cc524100e0f1709a9b38f9ea4353 to your computer and use it in GitHub Desktop.
Save kavunshiva/4840cc524100e0f1709a9b38f9ea4353 to your computer and use it in GitHub Desktop.
Generate a random string of ASCII characters
const generateRandomAsciiString = (len, cap=false, lower=false, num=false, special=false) => {
let str = '';
const includesCap = str => !![...Array(26)]
.map((n, i) => String.fromCharCode(i + 65))
.filter(c => str.includes(c)).length;
const includesLower = str => !![...Array(26)]
.map((n, i) => String.fromCharCode(i + 97))
.filter(c => str.includes(c)).length;
const includesNum = str => !![...Array(10)]
.map((n, i) => String.fromCharCode(i + 48))
.filter(c => str.includes(c)).length;
const includesSpecial = str => !![
...[...Array(15)].map((n, i) => String.fromCharCode(i + 33)),
...[...Array(7)].map((n, i) => String.fromCharCode(i + 58)),
...[...Array(4)].map((n, i) => String.fromCharCode(i + 123)),
].filter(c => str.includes(c)).length;
while (
!str.length ||
!((includesCap(str) || !cap)
&& (includesLower(str) || !lower)
&& (includesNum(str) || !num)
&& (includesSpecial(str) || !special))
) {
str = [...Array(90)]
.map((n, i) => String.fromCharCode(i + 37))
.sort(() => 0.5 - Math.random())
.slice(0,len)
.join('');
}
return str;
};
@kavunshiva
Copy link
Author

kavunshiva commented Nov 13, 2018

generates an ASCII string of random length.

inputs

name type description
len integer length of output string, in number of characters
cap boolean whether or not the output string must contain capital letters
lower boolean whether or not the output string must contain lower case letters
num boolean whether or not the output string must contain numerals
special boolean whether or not the output string must contain special characters

example usage

generateRandomAsciiString(10, true, false, true, false);
=> "$0<l#CYv]s"

[...Array(10)].forEach(() => console.log(generateRandomAsciiString(10, true, false, true, false)));
=>
`)(:6<3FKLA`
`V!"/3D6B%E`
`<1jM\h;ABy`
`@3mPVLJ+_q`
`No/0IH4Q>u`
`^o]N)P#7"q`
`Z'(@"%LNr0`
`m#[ReG.6FI`
`s@"MG')4H/`
`!p#S5UKndF`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment