-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
47 lines (34 loc) · 1.16 KB
/
index.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
// @flow
/* eslint-disable no-console, prefer-template */
type PrintNode<T> = (node: T, branch: string) => ?string;
type GetChildren<T> = (node: T) => Array<T>;
function printTree<T>(
initialTree: T,
printNode: PrintNode<T>,
getChildren: GetChildren<T>,
) {
function printBranch(tree, branch) {
const isGraphHead = branch.length === 0;
const children = getChildren(tree) || [];
let branchHead = '';
if (!isGraphHead) {
branchHead = children && children.length !== 0 ? '┬ ' : '─ ';
}
const toPrint = printNode(tree, `${branch}${branchHead}`);
if (typeof toPrint === 'string') {
console.log(`${branch}${branchHead}${toPrint}`);
}
let baseBranch = branch;
if (!isGraphHead) {
const isChildOfLastBranch = branch.slice(-2) === '└─';
baseBranch = branch.slice(0, -2) + (isChildOfLastBranch ? ' ' : '│ ');
}
const nextBranch = baseBranch + '├─';
const lastBranch = baseBranch + '└─';
children.forEach((child, index) => {
printBranch(child, children.length - 1 === index ? lastBranch : nextBranch);
});
}
printBranch(initialTree, '');
}
module.exports = printTree;