Last active
November 13, 2018 02:29
-
-
Save kavunshiva/4840cc524100e0f1709a9b38f9ea4353 to your computer and use it in GitHub Desktop.
Generate a random string of ASCII characters
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
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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
generates an ASCII string of random length.
inputs
len
integer
cap
boolean
lower
boolean
num
boolean
special
boolean
example usage