UNPKG

1.58 kBPlain TextView Raw
1export class DisjointSetItem<T>{
2 private parent: DisjointSetItem<T>;
3 private children: {[index: string]: DisjointSetItem<T>};
4
5 constructor(private value: T){
6 this.parent = null;
7 this.children = {};
8 }
9
10 public get Value(){
11 return this.value;
12 }
13
14 getKey(key?: keyof T){
15 if (key){
16 return this.value[key] + "";
17 }
18 return this.value + "";
19 }
20
21 getRoot(): DisjointSetItem<T>{
22 return this.isRoot() ? this : this.parent.getRoot();
23 }
24
25 isRoot(){
26 return this.parent === null;
27 }
28
29 /**
30 * 获取子集数量
31 */
32 getRank(){
33 if (Object.keys(this.children).length === 0){
34 return 0;
35 }
36 let rank = 0;
37 // tslint:disable-next-line:forin
38 for (const key in this.children){
39 rank++;
40 rank += this.children[key].getRank();
41 }
42 return rank;
43 }
44
45 getChildren(){
46 const arr: Array<DisjointSetItem<T>> = [];
47 // tslint:disable-next-line:forin
48 for (const key in this.children){
49 arr.push(this.children[key]);
50 }
51 return arr;
52 }
53
54 setParent(parent: DisjointSetItem<T>, forceSettingParentChild = true){
55 this.parent = parent;
56 if (forceSettingParentChild){
57 this.parent.addChild(this);
58 }
59 return this;
60 }
61
62 addChild(child: DisjointSetItem<T>){
63 this.children[child.getKey()] = child;
64 child.setParent(this, false);
65 return this;
66 }
67}
68export default DisjointSetItem;