-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.js
98 lines (84 loc) · 3.09 KB
/
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
94
95
96
97
98
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.TreeConsole = factory());
}(this, (function () { 'use strict';
var _defaultOptions = {
label: 'name',
children: 'children'
}
var _options;
/**
* extend tree array data
* @param arr
* @param parentData
*/
function extendTreeData (arr, parentData) {
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
// add property: last
item.last = i === (arr.length - 1);
if (parentData && parentData.parents) {
var parents = JSON.parse(JSON.stringify(parentData.parents));
parents.push({ last: parentData.last });
// add property: parents
item.parents = parents;
} else {
item.parents = [];
}
if (item[_options.children] && item[_options.children].length) {
extendTreeData(item[_options.children], item);
}
}
}
/**
* drawTree
* @param treeData
*/
/* renderData = [
'├── package.json',
'└── packages',
' ├── package-a',
' │ └── package.json',
' └── package-b',
' └── package.json'
] */
function drawTree (treeData, renderData) {
if (!renderData.length && treeData.length) {
renderData.push('·');
}
for (var i = 0; i < treeData.length; i++) {
var item = treeData[i];
var row = '';
var blankIndent = ' ';
var lineIndent = '│ ';
for (var j = 0; j < item.parents.length; j++) {
var pItem = item.parents[j];
if (pItem.last) {
row += blankIndent;
} else {
row += lineIndent;
}
}
var endLabel = (item.last ? '└── ' : '├── ') + item[_options.label];
row += endLabel;
renderData.push(row);
if (item[_options.children] && item[_options.children].length) {
drawTree(item[_options.children], renderData);
}
}
}
function getArrayTree () {
var renderData = [];
extendTreeData(TreeConsole.treeData);
drawTree(TreeConsole.treeData, renderData);
return renderData;
}
var TreeConsole = {};
TreeConsole.asTree = function (data, options) {
TreeConsole.treeData = data || [];
_options = options || _defaultOptions;
return getArrayTree().join('\n');
}
return TreeConsole;
})));