-
Notifications
You must be signed in to change notification settings - Fork 0
/
trees.js
65 lines (53 loc) · 1.48 KB
/
trees.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
// Trees
// Trees are graphs without cycles
// Cycles is three or more nodes connected in a circuitious path
// Graphs === have neighbors, not hierarchical
// Trees === have children, are hierarchical
function createNode(key) {
const children = [];
return {
key,
children,
addChild(childKey) {
const childNode = createNode(childKey);
children.push(childNode);
return childNode;
}
};
}
function createTree(rootKey) {
const root = createNode(rootKey);
return {
root,
print() {
let result = "";
function traverse(node, visitFn, depth) {
visitFn(node, depth);
if (node.children.length) {
node.children.forEach(child => {
traverse(child, visitFn, depth + 1);
});
}
}
function addKeyToResult(node, depth) {
result +=
result.length === 0
? node.key
: `\n${" ".repeat(depth * 2)}${node.key}`;
}
traverse(root, addKeyToResult, 1);
return result;
}
};
}
const dom = createTree("html");
const head = dom.root.addChild("head");
const body = dom.root.addChild("body");
const title = head.addChild("title - TREE LESSONS");
const header = body.addChild("header");
const main = body.addChild("main");
const footer = body.addChild("footer");
const h1 = header.addChild("h1 - tree lesson");
const p = main.addChild("p - all dat tree info");
const copyright = footer.addChild("Copyright 2018");
console.log(dom.print());