UNPKG

1.27 kBJavaScriptView Raw
1export class DisjointSetItem {
2 constructor(value) {
3 this.value = value;
4 this.parent = null;
5 this.children = {};
6 }
7 get Value() {
8 return this.value;
9 }
10 getKey(key) {
11 if (key) {
12 return this.value[key] + "";
13 }
14 return this.value + "";
15 }
16 getRoot() {
17 return this.isRoot() ? this : this.parent.getRoot();
18 }
19 isRoot() {
20 return this.parent === null;
21 }
22 getRank() {
23 if (Object.keys(this.children).length === 0) {
24 return 0;
25 }
26 let rank = 0;
27 for (const key in this.children) {
28 rank++;
29 rank += this.children[key].getRank();
30 }
31 return rank;
32 }
33 getChildren() {
34 const arr = [];
35 for (const key in this.children) {
36 arr.push(this.children[key]);
37 }
38 return arr;
39 }
40 setParent(parent, forceSettingParentChild = true) {
41 this.parent = parent;
42 if (forceSettingParentChild) {
43 this.parent.addChild(this);
44 }
45 return this;
46 }
47 addChild(child) {
48 this.children[child.getKey()] = child;
49 child.setParent(this, false);
50 return this;
51 }
52}
53export default DisjointSetItem;