Passed
Push — master ( 24656b...239482 )
by Christian
33:31 queued 21:33
created

code-generator.service.js ➔ getDigit   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
1
export default {
2
    generateCode,
3
    getPermutationCount,
4
    getRandomCharacter,
5
    getRandomNumber,
6
    getCharacters,
7
    getDigit
8
};
9
10
/**
11
 * Generates a new and random code with the provided string pattern.
12
 * Use the following placeholders to generate random characters and numbers in your code:
13
 * - '%s': random character
14
 * - '%d' - random number
15
 *
16
 * @example my-code_%s%s-%d%d
17
 * @param {String} pattern
18
 */
19
function generateCode(pattern) {
20
    let code = pattern;
21
22
    while (code.includes('%s')) {
23
        code = code.replace(new RegExp('%s'), getRandomCharacter());
24
    }
25
26
    while (code.includes('%d')) {
27
        code = code.replace(new RegExp('%d'), getRandomNumber());
28
    }
29
30
    return code;
31
}
32
33
/**
34
 * Gets the number of possible permutations of the
35
 * provided code pattern.
36
 *
37
 * @param {String} pattern
38
 */
39
function getPermutationCount(pattern) {
40
    const stringCount = (pattern.split('%s').length - 1);
41
    const digitCount = (pattern.split('%d').length - 1);
42
43
    // if no wildcards exist, then
44
    // we have at least 1 static permutation
45
    if (stringCount <= 0 && digitCount <= 0) {
46
        return 1;
47
    }
48
49
    // if we dont have a wildcard
50
    // make sure to have at least a count of * 1.
51
    // to avoid results of 0 when multiplying with 0.
52
    let stringSum = 1;
53
    let digitSum = 1;
54
55
    if (stringCount > 0) {
56
        stringSum = 52 ** stringCount;
57
    }
58
59
    if (digitCount > 0) {
60
        digitSum = 10 ** digitCount;
61
    }
62
63
    return (stringSum * digitSum);
64
}
65
66
function getRandomCharacter() {
67
    return getCharacters().charAt(Math.floor(Math.random() * Math.floor(getCharacters().length)));
68
}
69
70
function getRandomNumber() {
71
    return getDigit().charAt(Math.floor(Math.random() * Math.floor(getDigit().length)));
72
}
73
74
function getCharacters() {
75
    return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
76
}
77
78
function getDigit() {
79
    return '0123456789';
80
}
81