@@ -2,21 +2,43 @@ const { customAlphabet } = require("nanoid");
22
33/**
44 * @function `id` - Generate a unique ID composed of random characters and numbers.
5- * @param { Number } length - *Required* The length of the ID.
6- * @returns { String } - A unique ID string of a specified length (e.g. abthvmyt3h1j3it)
5+ * @param { Number } [length] - The length of each ID.
6+ * @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.
79 */
810
9- function id ( length ) {
11+ function generateId ( length , amount ) {
12+ let ids = [ ] ;
13+
14+ let i = 0 ;
15+
16+ do {
17+ const nanoid = customAlphabet ( "1234567890abcdefghijklmnopqrstuvwxyz" , length ) ;
18+ const id = nanoid ( ) ;
19+
20+ ids . push ( id ) ;
21+
22+ i ++ ;
23+ } while ( i < amount ) ;
24+
25+ if ( ids . length === 1 ) ids = ids [ 0 ] ;
26+
27+ return ids ;
28+ }
29+
30+ function id ( length , amount ) {
1031 if ( ! length ) throw new SyntaxError ( "No length specified" ) ;
11- if ( typeof length !== "number" ) throw new TypeError ( "Invalid type 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" ) ;
1238
13- const nanoid = customAlphabet (
14- "1234567890abcdefghijklmnopqrstuvwxyz" ,
15- length
16- ) ;
17- const id = nanoid ( ) ;
39+ if ( amount ) ids = amount ;
1840
19- return id ;
41+ return generateId ( length , amount ) ;
2042}
2143
2244module . exports = id ;
0 commit comments