@@ -7,14 +7,23 @@ import { InternalError } from '@rushstack/node-core-library';
7
7
* A disjoint set data structure
8
8
*/
9
9
export class DisjointSet < T extends object > {
10
- private _forest : WeakSet < T > ;
11
- private _parentMap : WeakMap < T , T > ;
12
- private _sizeMap : WeakMap < T , number > ;
10
+ private _forest : Set < T > ;
11
+ private _parentMap : Map < T , T > ;
12
+ private _sizeMap : Map < T , number > ;
13
+ private _setByElement : Map < T , Set < T > > | undefined ;
13
14
14
15
public constructor ( ) {
15
- this . _forest = new WeakSet < T > ( ) ;
16
- this . _parentMap = new WeakMap < T , T > ( ) ;
17
- this . _sizeMap = new WeakMap < T , number > ( ) ;
16
+ this . _forest = new Set < T > ( ) ;
17
+ this . _parentMap = new Map < T , T > ( ) ;
18
+ this . _sizeMap = new Map < T , number > ( ) ;
19
+ this . _setByElement = new Map < T , Set < T > > ( ) ;
20
+ }
21
+
22
+ public destroy ( ) : void {
23
+ this . _forest . clear ( ) ;
24
+ this . _parentMap . clear ( ) ;
25
+ this . _sizeMap . clear ( ) ;
26
+ this . _setByElement ?. clear ( ) ;
18
27
}
19
28
20
29
/**
@@ -28,6 +37,7 @@ export class DisjointSet<T extends object> {
28
37
this . _forest . add ( x ) ;
29
38
this . _parentMap . set ( x , x ) ;
30
39
this . _sizeMap . set ( x , 1 ) ;
40
+ this . _setByElement = undefined ;
31
41
}
32
42
33
43
/**
@@ -49,6 +59,24 @@ export class DisjointSet<T extends object> {
49
59
}
50
60
this . _parentMap . set ( y , x ) ;
51
61
this . _sizeMap . set ( x , this . _getSize ( x ) + this . _getSize ( y ) ) ;
62
+ this . _setByElement = undefined ;
63
+ }
64
+
65
+ public getAllSets ( ) : Iterable < Set < T > > {
66
+ if ( this . _setByElement === undefined ) {
67
+ this . _setByElement = new Map < T , Set < T > > ( ) ;
68
+
69
+ for ( const element of this . _forest ) {
70
+ const root : T = this . _find ( element ) ;
71
+ let set : Set < T > | undefined = this . _setByElement . get ( root ) ;
72
+ if ( set === undefined ) {
73
+ set = new Set < T > ( ) ;
74
+ this . _setByElement . set ( root , set ) ;
75
+ }
76
+ set . add ( element ) ;
77
+ }
78
+ }
79
+ return this . _setByElement . values ( ) ;
52
80
}
53
81
54
82
/**
0 commit comments