-
Notifications
You must be signed in to change notification settings - Fork 19
/
json-tree.js
93 lines (74 loc) · 1.8 KB
/
json-tree.js
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
module.exports = function jsonTree(json) {
var assets = json.assets
var modules = json.modules;
var maxDepth = 1;
var rootSize = 0;
var root = {
assets,
children: [],
name: 'root'
};
modules.forEach(function addToTree(module) {
var size;
if (module.source) {
size = module.source.length;
} else {
size = module.size;
}
rootSize += size;
var mod = {
id: module.id,
fullName: module.name,
size: size,
reasons: module.reasons
};
var depth = mod.fullName.split('/').length - 1;
if (depth > maxDepth) {
maxDepth = depth;
}
var fileName = mod.fullName;
var beginning = mod.fullName.slice(0, 2);
if (beginning === './') {
fileName = fileName.slice(2);
}
getFile(mod, fileName, root);
});
root.maxDepth = maxDepth;
root.size = rootSize;
return root;
}
function getFile(module, fileName, parentTree) {
var charIndex = fileName.indexOf('/');
if (charIndex !== -1) {
var folder = fileName.slice(0, charIndex);
if (folder === '~') {
folder = 'node_modules';
}
var childFolder = getChild(parentTree.children, folder);
if (!childFolder) {
childFolder = {
name: folder,
children: []
};
parentTree.children.push(childFolder);
}
getFile(module, fileName.slice(charIndex + 1), childFolder);
} else {
module.name = fileName;
parentTree.children.push(module);
}
}
function getChild(arr, name) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].name === name) {
return arr[i];
}
}
}
function dirsizes(child) {
return child.size = "size" in child
? child.size
: child.children.reduce(function(size, child) {
return size + ("size" in child ? child.size : dirsizes(child))
}, 0);
}