-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfastpass.js
78 lines (69 loc) · 2.82 KB
/
fastpass.js
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
var fastpass = (function () {
const charsets = {
lowercase: 'abcdefghijklmnopqrstuvwxyz',
uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
numbers: '0123456789',
symbols: '!@#$%^&*()_+-=[]{}|;:,.<>?'
};
const getRandomInt = (min, max) => {
const array = new Uint32Array(1);
crypto.getRandomValues(array);
return array[0] % (max - min + 1) + min;
};
const generateRandomString = (length, charset) => {
let result = '';
for (let i = 0; i < length; i++) {
const randomIndex = getRandomInt(0, charset.length - 1);
result += charset.charAt(randomIndex);
}
return result;
};
// Public API
return {
/**
* Generate a random string based on provided options.
* @param {Object} options - Options for string generation.
* @param {number} [options.length=12] - Length of the generated string.
* @param {string[]} [options.charsets=['lowercase', 'uppercase', 'numbers']] - Character sets to include.
* @param {boolean} [options.excludeSimilar=false] - Exclude similar looking characters.
* @param {boolean} [options.excludeAmbiguous=false] - Exclude ambiguous characters.
* @param {string} [options.customCharset] - A custom character set to use.
* @returns {string} The generated random string.
*/
generate: function (options = {}) {
const {
length = 12,
charsets: charsetsToUse = ['lowercase', 'uppercase', 'numbers'],
excludeSimilar = false,
excludeAmbiguous = false,
customCharset
} = options;
// Validate character sets
if (charsetsToUse.length === 0 && !customCharset) {
throw new Error('At least one character set must be selected or a custom charset must be provided.');
}
// Build the charset
let charset = customCharset || '';
if (!customCharset) {
for (const setName of charsetsToUse) {
if (charsets[setName]) {
charset += charsets[setName];
} else {
throw new Error(`Invalid character set: ${setName}`);
}
}
}
// Apply exclusions
if (excludeSimilar) {
charset = charset.replace(/[iloIO01]/g, '');
}
if (excludeAmbiguous) {
charset = charset.replace(/[{}()\[\]\/\\~<>;:.,'"\?]/g, '');
}
if (charset.length === 0) {
throw new Error('No valid characters available to generate a string.');
}
return generateRandomString(length, charset);
}
};
})();