This repository was archived by the owner on May 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
39 lines (32 loc) · 1.2 KB
/
index.js
File metadata and controls
39 lines (32 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
const lowercase = "abcdefghijklmnopqrstuvwxyz";
const uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const digits = "1234567890";
const symbols = "~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/";
function generateRandomString(nChars, constraints = {}) {
if (typeof nChars !== "number" || nChars < 0 || nChars % 1 !== 0) {
throw new TypeError(`nChars must be a whole number`);
}
const retval = [];
let allowed = "";
if (Object.keys(constraints).length === 0) {
allowed = lowercase + uppercase + digits + symbols;
} else {
if (constraints.lowercase) allowed += lowercase;
if (constraints.uppercase) allowed += uppercase;
if (constraints.digits) allowed += digits;
if (constraints.symbols) allowed += symbols;
}
if (allowed.length === 0) {
if (nChars === 0) return "";
throw new Error(`Cannot generate a string if no characters are allowed!`);
}
for (let i = 0; i < nChars; i++) {
retval.push(allowed[Math.floor(allowed.length * Math.random())]);
}
return retval.join("");
}
generateRandomString.lowercase = lowercase;
generateRandomString.uppercase = uppercase;
generateRandomString.digits = digits;
generateRandomString.symbols = symbols;
module.exports = generateRandomString;