-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMonarchy.js
72 lines (57 loc) · 1.3 KB
/
Monarchy.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
class Node {
constructor(value) {
this.value = value;
this.children = [];
this.alive = true;
}
}
class Monarchy {
constructor(value) {
const node = new Node(value);
this.node = node;
//! use an internal hash map for O(1) access
this._nodes = {};
this._nodes[value] = node;
}
_findNode(value) {
if (this._nodes[value]) {
return this._nodes[value];
}
return false;
}
birth(childValue, parentValue) {
//! find parent
const parentNode = this._findNode(parentValue);
if (parentNode) {
//! build childNode
const childNode = new Node(childValue);
parentNode.children.push(childNode);
//! add new child node to nodes
this._nodes[childValue] = childNode;
}
return false;
}
death(nodevalue) {
//! find parent
const parentNode = this._findNode(nodevalue);
if (parentNode) {
parentNode.alive = false;
}
return false;
}
getOrderOfSucession() {
//! runs a preorder dfs
let queue = [this.node];
let order = [];
while (queue.length > 0) {
const first = queue.shift();
if (first.alive) {
order.push(first.value);
}
const { children } = first;
queue = [...children, ...queue];
}
return order;
}
}
export default Monarchy;