-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
64 lines (58 loc) · 1.7 KB
/
index.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
"use strict";
const {
alphabetSortedFull,
alphabetLowerSorted,
alphabetLowerKeyboard,
alphabetLowerKeyboardInverted,
alphabetUpperSorted,
alphabetUpperKeyboard,
alphabetUpperKeyboardInverted,
} = require("./lib/alphabet");
const { numbersSorted, numbersInvert } = require("./lib/numbers");
const { jrand } = require("just-random-number");
const MAX_LENGTH = 24;
const symbolsList = [
alphabetSortedFull,
`${alphabetLowerSorted}${alphabetUpperSorted}`,
`${alphabetLowerKeyboard}${alphabetUpperKeyboard}`,
`${alphabetLowerKeyboardInverted}${alphabetUpperKeyboardInverted}`,
numbersSorted,
numbersInvert,
];
exports.juidFromSymbols = (symbols, minLength, maxLength = MAX_LENGTH) => {
if(typeof symbols === "undefined" || symbols === "") {
throw new Error("The field 'symbols' cannot be empty or undefined");
}
return generate(minLength, maxLength, symbols);
};
exports.juid = (minLength, maxLength = MAX_LENGTH) => {
return generate(minLength, maxLength, symbolsList);
};
function generate(minLength, maxLength, symbols) {
const length = getLength(minLength, maxLength);
let id = "";
for (let i = 0; i < length; i++) {
const randSymbs = symbols[jrand(0, symbols.length - 1)];
id += randSymbs[jrand(0, randSymbs.length - 1)];
}
return id;
}
function getLength(minLength, maxLength) {
if (minLength) {
if (minLength < 1 && maxLength < 1) {
return jrand(1, 25);
}
if (minLength === maxLength) {
return maxLength;
}
if (maxLength < 1) {
return minLength;
}
if (maxLength < 1) {
return minLength;
}
return minLength < maxLength ? jrand(minLength, maxLength) : jrand(maxLength, minLength);
} else {
return maxLength;
}
}