All files / src/utils group-services.js

100% Statements 32/32
100% Branches 8/8
100% Functions 6/6
100% Lines 32/32
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    2x 2x   2x 19x 9x   9x 3x 3x 3x 3x   3x   6x       19x 31x 6x   6x         2x 13x 13x   13x 25x 25x 25x 20x 7x   20x 2x   20x     25x     13x   13x     2x  
'use strict';
 
const isObject = require('lodash/isObject');
const Path = require('path');
 
const joinGroups = groups => {
    const innerJoin = (key, groups) => {
        const innerKeys = Object.keys(groups[key]);
 
        if (innerKeys.length === 1) {
            const innerKey = innerKeys[0];
            const newKey = Path.join(key, innerKey);
            groups[newKey] = groups[key][innerKey];
            delete groups[key];
 
            innerJoin(newKey, groups);
        } else {
            joinGroups(groups[key]);
        }
    };
 
    Object.keys(groups).forEach(key => {
        if (typeof groups[key] === 'object') {
            const innerKeys = Object.keys(groups[key]);
 
            innerJoin(key, groups);
        }
    });
};
 
const groupServices = services => {
    const groups = {};
    const paths = Object.keys(services).sort();
 
    paths.forEach(path => {
        let hash = groups;
        const parts = path.split(Path.sep);
        parts.slice(0, parts.length - 1).forEach((part, index) => {
            if (!hash[part]) {
                hash[part] = {};
            }
            if (typeof hash[part] !== 'object') {
                hash[part] = { '.': true };
            }
            hash = hash[part];
        });
 
        hash[parts[parts.length - 1]] = true;
    });
 
    joinGroups(groups);
 
    return groups;
};
 
module.exports = groupServices;