-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
90 lines (74 loc) · 2.31 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
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
const Node = require('./lib/node')
const TreeUtil = (function() {
/**
* Gets the iterator of the tree from the given root node.
* This will iterate the nodes like they were traversed in a pre-order fashion
*
* @returns iterable
*/
function getPreOrderIterable(rootNode) {
if (!(rootNode instanceof Node)) {
throw new TypeError('Parameter rootNode must be of Node type')
}
// to generate an iterator, a stack data structure will be created
// the nodes will be pushed to this stack as if they were traversed in pre order
// initially add the root node to the top of stack
let nodeStack = [rootNode]
return {
[Symbol.iterator]: () => {
return {
next: () => {
// process the "current parent"
let nextNode = nodeStack.pop()
// check if there are children to be processed next
if (nextNode && !nextNode.isLeaf()) {
let childrenReversed = [...nextNode.children].reverse()
nodeStack.push(...childrenReversed)
}
if (nextNode) {
return {value: nextNode, done: false}
}
else {
return {done: true}
}
}
}
}
}
}
function getDepthFirstIterable(rootNode) {
if (!(rootNode instanceof Node)) {
throw new TypeError('Parameter rootNode must be of Node type')
}
let nodeStack = [rootNode]
return {
[Symbol.iterator]: () => {
return {
next: () => {
// process the "current parent"
let nextNode = nodeStack.pop()
// check if there are children to be processed next
if (nextNode && !nextNode.isLeaf()) {
let childrenReversed = [...nextNode.children].reverse()
nodeStack.unshift(...childrenReversed)
}
if (nextNode) {
return {value: nextNode, done: false}
}
else {
return {done: true}
}
}
}
}
}
}
return {
getPreOrderIterable : getPreOrderIterable,
getDepthFirstIterable : getDepthFirstIterable
}
})()
module.exports = {
Node : Node,
TreeUtil : TreeUtil
}