Created
May 27, 2020 20:06
-
-
Save apotox/ef7e2589d181a7f6606fcae5faa6e518 to your computer and use it in GitHub Desktop.
javascript random string generator with options
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
export const namer = ({ | |
length = 5, | |
useDigit = true, | |
useAlpha = true, | |
upperOnly = false, | |
lowerOnly = false, | |
}) => { | |
let str = []; | |
let stock = []; | |
if (useDigit) { | |
stock = stock.concat( | |
Array(10) | |
.fill(0) | |
.map((_, j) => j), | |
); | |
} | |
if (useAlpha) { | |
if (upperOnly) { | |
stock = stock.concat( | |
Array(26) | |
.fill(0) | |
.map((_, j) => String.fromCharCode(j + 65)), | |
); | |
} else if (lowerOnly) { | |
stock = stock.concat( | |
Array(26) | |
.fill(0) | |
.map((_, j) => String.fromCharCode(j + 97)), | |
); | |
} else { | |
stock = stock.concat( | |
Array(26) | |
.fill(0) | |
.map((_, j) => String.fromCharCode(j + 65)), | |
); | |
stock = stock.concat( | |
Array(26) | |
.fill(0) | |
.map((_, j) => String.fromCharCode(j + 97)), | |
); | |
} | |
} | |
for (let i = 0; i < length; i++) { | |
str = str.concat(stock[Math.floor(Math.random() * stock.length)]); | |
} | |
return str.join(''); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment