forked from from74/referral-codes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
67 lines (54 loc) · 1.77 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
65
66
67
const PLACEHOLDER = '#';
const CHARSETS = {
NUMBERS: 'numbers',
ALPHABETIC: 'alphabetic',
ALPHANUMERIC: 'alphanumeric',
};
const size = (fn, array) =>
fn ? Array.from(array).filter((x) => fn(x)).length : array.length;
const randomInt = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;
const randomElement = (array) => array[randomInt(0, array.length - 1)];
const charsets = {
[CHARSETS.NUMBERS]: '0123456789',
[CHARSETS.ALPHABETIC]: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
[CHARSETS.ALPHANUMERIC]:
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
};
const charset = (name) => charsets[name];
const createConfig = (config = {}) => ({
count: config.count || 1,
length: config.length || 8,
charset: config.charset || charset(CHARSETS.ALPHANUMERIC),
prefix: config.prefix || '',
postfix: config.postfix || '',
pattern: config.pattern || PLACEHOLDER.repeat(config.length || 8),
});
const generateOne = ({ pattern, charset, prefix, postfix }) => {
// eslint-disable-next-line unicorn/no-reduce
const code = Array.from(pattern).reduce(
(acc, cur) => acc + (cur === PLACEHOLDER ? randomElement(charset) : cur),
'',
);
return `${prefix}${code}${postfix}`;
};
const isFeasible = (charset, pattern, count) => {
return charset.length ** size((x) => x === PLACEHOLDER, pattern) >= count;
};
const generate = (config) => {
config = createConfig(config);
const { charset, count, pattern } = config;
if (!isFeasible(charset, pattern, count)) {
throw new Error('Not possible to generate requested number of codes.');
}
const codes = new Set();
while (codes.size < count) {
codes.add(generateOne(config));
}
return Array.from(codes);
};
module.exports = {
generate,
charset,
CHARSETS,
};