All files / src utils.js

100% Statements 115/115
89.23% Branches 58/65
100% Functions 23/23
100% Lines 107/107

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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  33x   33x               53x                       33x               33x                   33x 20x 92x                 33x 60x 60x   60x 60x   60x 59x 104x 98x     6x     53x                 33x   22x 22x 1x   21x 21x   1x   20x               33x 6x 1x   5x 5x 5x               33x             33x 3x 3x 3x 1x 9x 5x 2x                     33x 31x 31x 31x 31x 31x     31x 24x 23x   24x 1x   24x       31x   31x 41x 29x     12x 23x     2x 2x 21x 17x 17x 1x 16x 1x   15x                         4x 3x 3x 2x 2x       2x 2x   21x     2x     33x 15x 15x   1x   14x     33x 16x   68x   16x   62x 160x   51x 51x 18x       18x 1x 1x 1x 1x   17x   50x   46x 46x       61x       45x   33x 1x   4x       33x                                
/* eslint-disable no-console */
const fs = require('fs'),
    // eslint-disable-next-line quotes
    NL = "\n",
 
    /**
        * Creates an entry. element
        *
        * @param      {<type>}            path    The path
        * @return     {(Object|boolean)}  { description_of_the_return_value }
        */
    createEntry = path => fs.existsSync(path) && {
        content: fs.readFileSync(path).toString(),
        time: fs.statSync(path).mtime.getTime(),
        cachevalid: true
    },
 
    /**
     * Gets the file extension.
     *
     * @param      {<type>}  fname   The filename
     * @return     {<type>}  The file extension.
     */
    getFileExtension = fname => (fname.split('.').pop()),
 
    /**
     * Gets the file time.
     *
     * @param      {<type>}  path    The path
     * @return     {<type>}  The file time.
     */
    getFileTime = thepath => fs.existsSync(thepath)
        && fs.statSync(thepath).mtime.getTime(),
 
    /**
     * get a unique array given an array
     *
     * @param      {<type>}  a       { parameter_description }
     * @return     {Array}   { description_of_the_return_value }
     */
    // uniquearr: a => a.filter((el, i) => a.indexOf(el) == i),
    uniquearr = a => {
        const h = {};
        return a.filter(el => h[el] ? false : (h[el] = true));
    },
 
    /**
     * checks if a ns exists
     *
     * @param      {<type>}           ns      { parameter_description }
     * @param      {(number|string)}  ctx     The context
     */
    checkns = (ns, ctx) => {
        const els = ns.split(/\.|\//),
            l = els.length;
 
        let i = 0;
        ctx = (ctx !== undefined) ? ctx : {};
 
        if (!ns) return ctx;
        for (null; i < l; i += 1) {
            if (typeof ctx[els[i]] !== 'undefined') {
                ctx = ctx[els[i]];
            } else {
                // break it
                return undefined;
            }
        }
        return ctx;
    },
 
    /**
     * json from a string
     *
     * @param      {string}   s       { parameter_description }
     * @return     {boolean}  { description_of_the_return_value }
     */
    jsonFromStr = s => {
        // eslint-disable-next-line prefer-const
        let r = {};
        if (s === undefined) {
            return false;
        }
        try {
            eval(`r = {${s}}`);
        } catch (e) {
            return r;
        }
        return r;
    },
 
    /**
     * [isArray description]
     * @param  {[type]}  o [description]
     * @return {Boolean}   [description]
     */
    isArray = o => {
        if (Array.isArray && Array.isArray(o)) {
            return true;
        }
        const t1 = String(o) !== o,
            t2 = {}.toString.call(o).match(/\[object\sArray\]/);
        return t1 && !!(t2 && t2.length);
    },
 
    /**
     * [isString description]
     * @param  {[type]}  o [description]
     * @return {Boolean}   [description]
     */
    isString = o => typeof o === 'string' || o instanceof String,
 
    /**
     * [getIterator description]
     * @param  {Array} els [description]
     * @return {Iterator}     [description]
     */
    getIterator = els => {
        let i = 0;
        const len = els.length;
        return {
            reset: () => { i = 0; },
            hasNext: () => i < len,
            next: () => els[i++],
            size: () => len
        };
    },
 
    /**
     * [replaceAll description]
     * @param  {[type]} tpl     [description]
     * @param  {[type]} obj     [description]
     * @param  {[type]} options [description]
     * @return {[type]}         [description]
     */
    replaceAll = (tpl, obj, options) => {
        let start = '%',
            end = '%',
            fb = null,
            clean = false,
            straight = true,
            tmp, last;
 
        if (typeof options !== 'undefined') {
            if ('delim' in options) {
                [start, end] = options.delim;
            }
            if ('fb' in options) {
                fb = options.fb;
            }
            clean = !!options.clean;
        }
 
        // reg = new RegExp('\\' + start + '(\\\+)?([A-z0-9-_\.]*)' + '\\' + end, 'g');
        const reg = new RegExp(`\\${start}(\\+)?([A-z0-9-_.]*)\\${end}`, 'g');
 
        while (straight) {
            if (!(tpl.match(reg))) {
                return tpl;
            }
            // eslint-disable-next-line complexity
            tpl = tpl.replace(reg, (str, enc, $1, _t) => {
                if (typeof obj === 'function') {
                    /**
                     * avoid silly infiloops */
                    tmp = obj($1);
                    _t = (tmp !== start + $1 + end) ? obj($1) : $1;
                } else if ($1 in obj) {
                    _t = typeof obj[$1];
                    if (_t === 'function') {
                        _t = obj[$1]($1);
                    } else if (_t === 'object') {
                        _t = '';
                    } else {
                        _t = obj[$1];
                    }
                    // incomplete when the placeholder points to a object (would print)
                    // _t = typeof obj[$1] === 'function' ? obj[$1]($1) : obj[$1];
 
                    /**
                        * not a function and not found in literal
                        * use fallback if passed or get back the placeholder
                        * switching off before returning
                        */
                } else {
                    /* @ least check for ns, in case of dots
                    */
                    if ($1.match(/\./)) {
                        last = checkns($1, obj);
                        if (last) {
                            _t = enc ? encodeURIComponent(last) : last;
                            return typeof last === 'function' ? last($1) : last;
                        }
                    }
                    // but do not go deeper
                    straight = false;
                    _t = fb !== null ? fb($1) : clean ? '' : start + $1 + end;
                }
                return enc ? encodeURIComponent(_t) : _t;
            });
        }
        return tpl;
    },
 
    validateJson = json => {
        try {
            JSON.parse(json);
        } catch (e) {
            return false;
        }
        return true;
    },
 
    solveJson = (obj, lim) => {
        let maxSub = lim || 1E3;
 
        const aVarIn = v => v.match(/\$([A-z0-9-_/.]+)\$/);
 
        return (function _ (o) {
            let y, j;
            for (j in o) {
                switch (typeof o[j]) {
                    case 'string':
                        y = aVarIn(o[j]);
                        while (y) {
                            o[j] = o[j].replace(
                                `$${y[1]}$`,
                                checkns(y[1], obj) || ''
                            );
                            if (maxSub-- < 0) {
                                console.log('[ERROR] it seems like variable json has looping placeholders!');
                                const e = new Error();
                                e.stop = true;
                                throw e;
                            }
                            y = aVarIn(o[j]);
                        }
                        break;
                    case 'object':
                        o[j] = _(o[j]);
                        break;
                    default: ;
                }
            }
            return o;
        })(obj);
    },
 
    cleanJson = json => json.replace(/(^[\s\t]*\/\*([\s\S]*?)\*\/)|(^[\s\t]*\/\/(.*)$)/gm, ''),
 
    replaceLinenumbers = tpl => (
        tpl.split(NL)
            .map(
                (line, i) => line.replace(/__LINE__/g, i + 1)
            ).join(NL)
    );
 
module.exports = {
    cleanJson,
    createEntry,
    getFileExtension,
    getFileTime,
    uniquearr,
    checkns,
    jsonFromStr,
    isArray,
    isString,
    getIterator,
    replaceAll,
    replaceLinenumbers,
    validateJson,
    solveJson
};