I have a flat list of directories:
var directories = [
{ path: '/a', status: 0 },
{ path: '/a/a', status: 1 },
{ path: '/a/b', status: 1 },
{ path: '/a/c', status: 0 },
{ path: '/b', status: 0 },
{ path: '/b/a', status: 0 },
{ path: '/b/b', status: 1 },
{ path: '/c', status: 0 },
{ path: '/c/a', status: 2 },
{ path: '/c/b', status: 0 },
{ path: '/c/c', status: 1 },
{ path: '/c/d', status: 1 },
{ path: '/d', status: 0 },
{ path: '/d/a', status: 1 },
{ path: '/e', status: 1 },
{ path: '/e/a', status: 0 }
];
I would like to have the total children of each directory and the totals of those childrens by their status number e.g.
{ path: '/a', status: 0, child_total: 3, child_status-0: 1, child_status-1: 2 }
I believe the best way to do this is to create an Object containing named paths, then loop through each parent of a directory and add one to each total.
Using this approach I've created these functions:
function increment(item, attr) {
if (!item[attr]) { item[attr] = 0; }
item[attr] += 1;
};
function calculate(items) {
var i = 0;
var list = {};
// for each directory
for (i = 0; i < items.length; i += 1) {
// if the directory stats already exist, merge in directory info
list[items[i].path] = list[items[i].path] ? Object.assign(list[items[i].path], items[i]) : items[i];
var j = 0;
var parts = items[i].path.split('/');
var path = '';
// loop through it's parents
for (j = 1; j < parts.length; j += 1) {
path += '/' + parts[j];
// increment the parent's totals
if (path !== items[i].path) {
if (!list[path]) { list[path] = {}; }
increment(list[path], 'child_total');
increment(list[path], 'child_status-' + items[i].status);
}
}
}
return list;
}
Here is a working fiddle:
https://jsfiddle.net/kmturley/b955d3mb/1/
This is the directory browser I'm looking to use the structure on:
https://jsfiddle.net/kmturley/x93pcd60/
I'm planning to run this function on thousands of items so performance is very important. I'm wondering if this is the best approach?
Is there a better way? without a loop within a loop? Maybe a RegEx for splitting the paths?
Any suggestions would help!