|
1 | | -const { customAlphabet } = require("nanoid"); |
2 | | - |
3 | 1 | /** |
4 | 2 | * @function `id` - Generate a unique ID composed of random characters and numbers. |
5 | 3 | * @param { Number } [length] - The length of each ID. |
6 | 4 | * @param { Number } [amount] - The amount of IDs to generate. Condition: **`1 < amount < 64`** |
7 | | - * @returns { Array } - Returns an array if the amount inputted is above 1. |
8 | | - * @returns { String } - Returns a string if the amount inputted is equal to 1. |
| 5 | + * @returns { string | string[] } - Returns an array if the amount inputted is above 1, else returns a string. |
9 | 6 | */ |
10 | 7 |
|
11 | | -function generateId(length, amount) { |
12 | | - let ids = []; |
| 8 | +const { customAlphabet } = require("nanoid"); |
| 9 | + |
| 10 | +module.exports = function id(length, amount) { |
| 11 | + if (!length) throw new SyntaxError("No length specified"); |
| 12 | + if (typeof length !== "number") throw new TypeError("Length must be Number type"); |
| 13 | + |
| 14 | + let ids = 1; |
| 15 | + |
| 16 | + if (amount && !isFinite(amount)) throw new TypeError("Amount must be Number type"); |
| 17 | + if ((amount && amount < 1) || (amount && amount >= 64)) throw new RangeError("Amount must be equal or higher than 1 and lower than 64"); |
| 18 | + |
| 19 | + if (amount) ids = amount; |
| 20 | + |
| 21 | + let generatedIds = []; |
13 | 22 |
|
14 | 23 | let i = 0; |
15 | 24 |
|
16 | 25 | do { |
17 | 26 | const nanoid = customAlphabet("1234567890abcdefghijklmnopqrstuvwxyz", length ); |
18 | 27 | const id = nanoid(); |
19 | 28 |
|
20 | | - ids.push(id); |
| 29 | + generatedIds.push(id); |
21 | 30 |
|
22 | 31 | i++; |
23 | 32 | } while (i < amount); |
24 | 33 |
|
25 | | - if (ids.length === 1) ids = ids[0]; |
| 34 | + if (generatedIds.length === 1) return generatedIds[0]; |
26 | 35 |
|
27 | | - return ids; |
| 36 | + return generatedIds; |
28 | 37 | } |
29 | | - |
30 | | -function id(length, amount) { |
31 | | - if (!length) throw new SyntaxError("No length specified"); |
32 | | - if (typeof length !== "number") throw new TypeError("Length must be Number type"); |
33 | | - |
34 | | - let ids = 1; |
35 | | - |
36 | | - if (amount && !isFinite(amount)) throw new TypeError("Amount must be Number type"); |
37 | | - if ((amount && amount < 1) || (amount && amount >= 64)) throw new RangeError("Amount must be equal or higher than 1 and lower than 64"); |
38 | | - |
39 | | - if (amount) ids = amount; |
40 | | - |
41 | | - return generateId(length, amount); |
42 | | -} |
43 | | - |
44 | | -module.exports = id; |
0 commit comments