-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
55 lines (48 loc) 路 1.49 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
'use strict';
/* DEPENDENCIES */
const { randomBytes } = require('crypto');
const { promisify, callbackify } = require('util');
const DEFAULT_CHARS = 'ABCDEFGHIJKLMNPQRSTUWXYZ123456789'; // 24 CHARS + 9 NUMBERS
const DEFAULTS = {
length: 6,
chars: DEFAULT_CHARS,
separator: '-',
groups: 1
};
const copyObject = object => JSON.parse(JSON.stringify(object));
/* EXPORTS GENERATE FUNCTION */
exports.generate = (options, callback) => {
if (!options) options = {};
if (typeof options === 'number') options = { length: options };
if (callback) options.asyncronous = true;
options = Object.assign(copyObject(DEFAULTS), options);
// RETURN VALUE OR FUNCTION
if (options.function) {
return () => generateSyncronous(options);
} else if (options.asyncronous && callback) {
return callbackify(generateAsyncronous)(options, callback);
} else if (options.asyncronous) {
return generateAsyncronous(options);
} else {
return generateSyncronous(options);
}
};
/* HELPER FUNCTIONS */
function generateSyncronous ({ length, chars }) {
let random = randomBytes(length);
return bytesToId(random, { length, chars });
}
async function generateAsyncronous ({ length, chars }) {
try {
const random = await promisify(randomBytes)(length);
return bytesToId(random, { length, chars });
} catch (error) {
throw error;
}
}
function bytesToId (bytes, { length, chars }) {
return new Array(length)
.fill()
.map((value, index) => chars[bytes[index] % chars.length])
.join('');
}