Skip to content

Instantly share code, notes, and snippets.

@apotox
Created May 27, 2020 20:06
Show Gist options
  • Save apotox/ef7e2589d181a7f6606fcae5faa6e518 to your computer and use it in GitHub Desktop.
Save apotox/ef7e2589d181a7f6606fcae5faa6e518 to your computer and use it in GitHub Desktop.
javascript random string generator with options
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