Code coverage report for src/Utils.ts

# All files / src Utils.ts

98.11% Statements 104/106
90% Branches 27/30
100% Functions 4/4
98.06% Lines 101/103

    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
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    3211x

    1x

    1x

    1x

    1x

    1x

    117012x

    530x
    1x

    529x
    14x

    515x
    515x

    515x
    153437x
    153437x

    515x

    8x

    8x

    8x
    805x

    8x

    3436x

    3436x

    3436x

    8x

    105200x

    105200x

    10x

    10x
    7x

    3x

    10x

    10x

    71222x

    176159x

    176159x

    176159x

    55853x

    54215x
    54215x
    54215x
    54215x

    54215x

    5x

    5x
    5x
    5x
    5x

    5x
    370x
    191x

    179x

    5x

    5x

    5x

    5x

    5x
    5x

    5x

    51482x

    34x
    34x
    6x

    1x

    2x
    2x
    2x
    2x

    2x
    512x

    2x
    512x
    512x
    512x
    512x

    2x
    2x

    2x
    9x
    9x
    9x
    9x
    9x
    9x

    2x

    20x

    3x

    1x

    6x

    83073x

    83073x
    83073x
    83073x

    83073x
    528067x
    523000x
    523000x

    5067x
    5067x

    528067x

     import { Chance } from 'chance';

    import { JSFuck } from './enums/JSFuck';

    const isEqual = require('is-equal');

    export class Utils {
        /**
         * @type {string}
         */
        public static readonly randomGeneratorPool: string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

        /**
         * @type {Chance.Chance | Chance.SeededChance}
         */
        private static randomGenerator: Chance.Chance | Chance.SeededChance = new Chance();

        /**
         * @param array
         * @param searchElement
         * @returns {boolean}
         */
        public static arrayContains (array: any[], searchElement: any): boolean {
            return array.indexOf(searchElement) >= 0;
        }

        /**
         * @param array
         * @param times
         * @returns {T[]}
         */
        public static arrayRotate <T> (array: T[], times: number): T[] {
            if (!array.length) {
                throw new ReferenceError(`Cannot rotate empty array.`);
            }

            if (times <= 0) {
                return array;
            }

            let newArray: T[] = array,
                temp: T | undefined;

            while (times--) {
                temp = newArray.pop()!;
                newArray.unshift(temp);
            }

            return newArray;
        }

        /**
         * @param string
         */
        public static btoa (string: string): string {
            const chars: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';

            let output: string = '';

            string = encodeURIComponent(string).replace(/%([0-9A-F]{2})/g, (match, p1) => {
                return String.fromCharCode(parseInt('0x' + p1));
            });

            for (
                let block: number|undefined, charCode: number, idx: number = 0, map: string = chars;
                string.charAt(idx | 0) || (map = '=', idx % 1);
                output += map.charAt(63 & block >> 8 - idx % 1 * 8)
            ) {
                charCode = string.charCodeAt(idx += 3/4);

                Iif (charCode > 0xFF) {
                    throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
                }

                block = block << 8 | charCode;
            }

            return output;
        }

        /**
         * @param dec
         * @returns {string}
         */
        public static decToHex (dec: number): string {
            const radix: number = 16;

            return Number(dec).toString(radix);
        }

        /**
         * @param url
         * @returns {string}
         */
        public static extractDomainFromUrl (url: string): string {
            let domain: string;

            if (url.indexOf('://') > -1 || url.indexOf('//') === 0) {
                domain = url.split('/')[2];
            } else {
                domain = url.split('/')[0];
            }

            domain = domain.split(':')[0];

            return domain;
        }

        /**
         * @param min
         * @param max
         * @returns {number}
         */
        public static getRandomFloat (min: number, max: number): number {
            return Utils.getRandomGenerator().floating({
                min: min,
                max: max,
                fixed: 7
            });
        }

        /**
         * @returns {Chance.Chance}
         */
        public static getRandomGenerator (): Chance.Chance {
            const randomGenerator: Chance.Chance = Utils.randomGenerator;

            Iif (!randomGenerator) {
                throw new Error(`\`randomGenerator\` static property is undefined`);
            }

            return Utils.randomGenerator;
        }

        /**
         * @param min
         * @param max
         * @returns {number}
         */
        public static getRandomInteger (min: number, max: number): number {
            return Utils.getRandomGenerator().integer({
                min: min,
                max: max
            });
        }

        /**
         * @param length
         * @returns {string}
         */
        public static getRandomVariableName (length: number = 6): string {
            const rangeMinInteger: number = 10000,
                rangeMaxInteger: number = 99999999,
                prefix: string = '_0x';

            return `${prefix}${(
                Utils.decToHex(
                    Utils.getRandomInteger(rangeMinInteger, rangeMaxInteger)
                )
            ).substr(0, length)}`;
        }

        /**
         * @param str
         * @param length
         * @returns {string[]}
         */
        public static hideString(str: string, length: number): [string, string] {
            const escapeRegExp: (s: string) => string = (s: string) =>
                s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

            const randomMerge: (s1: string, s2: string) => string = function (s1: string, s2: string): string {
                let i1: number = -1,
                    i2: number = -1,
                    result: string = '';

                while (i1 < s1.length || i2 < s2.length) {
                    if (Utils.getRandomFloat(0, 1) < 0.5 && i2 < s2.length) {
                        result += s2.charAt(++i2);
                    } else {
                        result += s1.charAt(++i1);
                    }
                }

                return result;
            };

            const randomString: string = Utils.randomGenerator.string({
                length: length,
                pool: Utils.randomGeneratorPool
            });

            let randomStringDiff: string = randomString.replace(
                new RegExp('[' + escapeRegExp(str) + ']', 'g'),
            '');

            const randomStringDiffArray: string[] = randomStringDiff.split('');

            Utils.randomGenerator.shuffle(randomStringDiffArray);
            randomStringDiff = randomStringDiffArray.join('');

            return [randomMerge(str, randomStringDiff), randomStringDiff];

        }

        /**
         * @param number
         * @returns {boolean}
         */
        public static isInteger (number: number): boolean {
            return number % 1 === 0;
        }

        /**
         * @param map
         * @param value
         * @returns {any}
         */
        public static mapGetFirstKeyOf(map: Map <any, any>, value: any): any {
            for (var [key, storageValue] of map) {
                if (isEqual(value, storageValue)) {
                    return key;
                }
            }

            return null;
        }

        /**
         * RC4 symmetric cipher encryption/decryption
         * https://gist.github.com/farhadi/2185197
         *
         * @param key
         * @param string
         * @returns {string}
         */
        public static rc4 (string: string, key: string) {
            let s: number[] = [],
                j: number = 0,
                x: number,
                result: string = '';

            for (var i = 0; i < 256; i++) {
                s[i] = i;
            }

            for (i = 0; i < 256; i++) {
                j = (j + s[i] + key.charCodeAt(i % key.length)) % 256;
                x = s[i];
                s[i] = s[j];
                s[j] = x;
            }

            i = 0;
            j = 0;

            for (let y = 0; y < string.length; y++) {
                i = (i + 1) % 256;
                j = (j + s[i]) % 256;
                x = s[i];
                s[i] = s[j];
                s[j] = x;
                result += String.fromCharCode(string.charCodeAt(y) ^ s[(s[i] + s[j]) % 256]);
            }

            return result;
        }

        /**
         * @param randomGenerator
         */
        public static setRandomGenerator (randomGenerator: Chance.Chance | Chance.SeededChance): void {
            Utils.randomGenerator = randomGenerator;
        }

        /**
         * @param obj
         * @returns {T}
         */
        public static strEnumify <T extends {[prop: string]: ''|string}> (obj: T): T {
            return obj;
        }

        /**
         * @param string
         * @returns {string}
         */
        public static stringToJSFuck (string: string): string {
            return Array
                .from(string)
                .map((character: string): string => {
                    return JSFuck[character] || character;
                })
                .join(' + ');
        }

        /**
         * @param string
         * @returns {string}
         */
        public static stringToUnicodeEscapeSequence (string: string): string {
            const radix: number = 16;

            let prefix: string,
                regexp: RegExp = new RegExp('[\x00-\x7F]'),
                template: string;

            return `${string.replace(/[\s\S]/g, (escape: string): string => {
                if (regexp.test(escape)) {
                    prefix = '\\x';
                    template = '0'.repeat(2);
                } else {
                    prefix = '\\u';
                    template = '0'.repeat(4);
                }

                return `${prefix}${(template + escape.charCodeAt(0).toString(radix)).slice(-template.length)}`;
            })}`;
        }
    }