all files / app/utils/ helper.ts

21% Statements 21/100
0% Branches 0/55
9.52% Functions 2/21
21.51% Lines 20/93
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            1×   1×   1×                                                                                                                 1×   1×         1×                         1×                                         1×                                             1×                                 1×                                                   1×                       1× 4×     1×                         1×                         1×                 1×           1×                             1×                 1×  
/* Copyright CloudLinux Zug GmbH 2010-2017 All Rights Reserved
 *
 * Licensed under CLOUD LINUX LICENSE AGREEMENT
 * http://cloudlinux.com/docs/LICENSE.TXT
 */
 
import { plainToClass } from 'class-transformer';
 
export class Helper  {
 
    private static formatUnit = {
        'byteinsec': {
            'next': 'kbinsec',
            'icon': 'B/s',
            'coefficient': 1024,
            'precision': 2,
        },
        'kbinsec': {
            'next': 'mbinsec',
            'icon': 'KB/s',
            'coefficient': 1024,
            'precision': 2,
        },
        'mbinsec': {
            'next': 'gbinsec',
            'icon': 'MB/s',
            'coefficient': 1024,
            'precision': 2,
        },
        'gbinsec': {
            'next': null,
            'icon': 'G/s',
            'coefficient': 1,
            'precision': 2,
        },
        'bytes': {
            'next': 'kilobytes',
            'icon': 'B',
            'coefficient': 1024,
            'precision': 2,
        },
        'kilobytes': {
            'next': 'megabytes',
            'icon': 'K',
            'coefficient': 1024,
            'precision': 2,
        },
        'megabytes': {
            'next': 'gigabytes',
            'icon': 'M',
            'coefficient': 1024,
            'precision': 2,
        },
        'gigabytes': {
            'next': null,
            'icon': 'G',
            'coefficient': 1,
            'precision': 2,
        },
        'percents': {
            'next': null,
            'icon': '%',
            'coefficient': 1,
            'precision': 0,
        }
    };
 
    public static timeout: Function = ms => new Promise(res => setTimeout(res, ms));
 
    public static isEmpty(obj){
        return (Object.getOwnPropertyNames(obj).length === 0);
    }
 
    // According to MDN web docs
    public static unicodeBase64ToString(base64String: string): string {
        return decodeURIComponent(Array.prototype.map.call(atob(base64String), c => {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));
    }
 
    /**
     * Checks for existing of property in object by full path to property.
     *
     * @param object
     * @param property string   Full property path separated by underscore.
     * @returns {boolean}
     */
    public static hasOwnPropetyRecursively(object, property) {
        let parts = property.split('_');
        let curObject = object;
        for (let part of parts) {
            if (curObject.hasOwnProperty(part)) {
                curObject = curObject[part];
            } else {
                return false;
            }
        }
        return true;
    }
 
    /**
     * Gets value of property in object by full path to property
     * if it exists.
     *
     * @param object
     * @param property   Full property path separated by underscore.
     * @returns {any}
     */
    public static getValueFromObjectRecursively(object, property) {
        if (Helper.hasOwnPropetyRecursively(object, property)) {
            let parts = property.split('_');
            let curObject = object;
            let lastValue: any;
            for (let part of parts) {
                curObject = curObject[part];
                if (typeof curObject != 'object') {
                    return curObject;
                }
            }
        } else {
            return null;
        }
    }
 
    /**
     * Checks equality of two arrays.
     *
     * @param array1
     * @param array2
     * @returns {boolean}
     */
    public static isArraysEqual(array1: any[], array2: any[]):boolean {
        if (array1.length !== array2.length) {
            return false;
        }
        for (let el of array1) {
            if (array2.indexOf(el) === -1) {
                return false;
            }
        }
        return true;
    }
 
    /**
     * Reformat value
     * @param rawValue
     * @param format
     */
    public static reformatValue(rawValue, format){
        if (!/^-?[\d.]+$/.test(rawValue) || typeof rawValue === 'undefined') {
            return { value: rawValue, rawValue: rawValue };
        }
        rawValue = Number(rawValue);
        let value = rawValue;
        if (value && typeof format !== 'undefined' && Helper.formatUnit.hasOwnProperty(format)){
            while (true) {
                let newValue = value / Helper.formatUnit[format]['coefficient'];
                if (Helper.formatUnit[format]['next'] === null || newValue < 1) {
                    break;
                }
                format = Helper.formatUnit[format]['next'];
                value = newValue;
            }
            value = parseFloat(value.toFixed(Helper.formatUnit[format]['precision'])) + (
                (parseFloat(value.toFixed(Helper.formatUnit[format]['precision'])) !== 0)
                    ? Helper.formatUnit[format]['icon'] : ''
            );
        }
        return {
            value,
            rawValue
        };
    }
 
    public static reformatToDirtyValue(value){
        var multiplier = 1;
        if(/K$/i.test(value) || /KB\/s$/i.test(value))
            multiplier = 1024;
        else if(/M$/i.test(value) || /MB\/s$/i.test(value))
            multiplier = 1048576;
        else if(/G$/i.test(value) || /G\/s$/i.test(value))
            multiplier = 1073741824;
 
        return parseFloat(String(value).replace(/[^\d.-]/g,'')) * multiplier;
    }
 
    public static isObject(o) {
        return 'object' === typeof o;
    }
 
    public static recursivelyAssign2(target, source){
        for (let field in target){
            if (Helper.isObject(target[field]) && Helper.isObject(source[field])){
                Helper.recursivelyAssign2(target[field], source[field]);
            }
        }
        for (let field in source){
            if (!Helper.isObject(target[field])){
                target[field] = source[field];
            }
        }
    }
 
    public static removeBranchFromObject(object, branch) {
        for (let key in branch) {
            if (!object.hasOwnProperty(key)) {
                continue;
            }
            if (typeof branch[key] === 'object') {
                Helper.removeBranchFromObject(object[key], branch[key]);
            } else {
                delete object[key];
            }
        }
    }
 
    public static isNumber(n: any) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    }
 
    /**
     * Convert dictionary to Class.
     * @param object
     * @param className
     */
    public static convertDictToClass(object, className) {
        Object.keys(object).forEach((item) => {
            object[item] = plainToClass(className, object[item]);
        });
    }
 
    public static comparePlainObjects(a: Object, b: Object): boolean {
        let aProps = Object.getOwnPropertyNames(a);
        let bProps = Object.getOwnPropertyNames(b);
        if (aProps.length !== bProps.length) {
            return false;
        }
        for (let i = 0; i < aProps.length; i++) {
            let propName = aProps[i];
            if (a[propName] !== b[propName]) {
                return false;
            }
        }
        return true;
    }
 
    public static convertStringToHexRepresentation(string: string) {
        if (typeof string !== 'string') return string;
        return string.split('')
            .map(letter => {
                return '\\u' + letter.charCodeAt(0).toString(16)
                    .toUpperCase().padStart(4, '0');
            })
            .join('');
    }
}