-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLWWSet.ts
50 lines (40 loc) · 1.09 KB
/
LWWSet.ts
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
import GSet from './GSet';
export default class LWWSet<T> {
public a: GSet<T>;
public at: Map<T, number>;
public r: GSet<T>;
public rt: Map<T, number>;
constructor() {
this.a = new GSet<T>();
this.at = new Map<T, number>();
this.r = new GSet<T>();
this.rt = new Map<T, number>();
}
public query(): Set<T> {
return new Set(
[...this.a.query()].filter(
(element) =>
!this.r.query().has(element) ||
this.at.get(element)! > this.rt.get(element)!,
),
);
}
public add(element: T): void {
this.a.add(element);
this.at.set(element, Date.now());
}
public remove(element: T): void {
this.r.add(element);
this.rt.set(element, Date.now());
}
public merge(set: LWWSet<T>) {
this.a.merge(set.a);
this.r.merge(set.r);
[...this.at.keys(), ...set.at.keys()].map((key) => {
this.at.set(key, Math.max(this.at.get(key) ?? 0, set.at.get(key) ?? 0));
});
[...this.rt.keys(), ...set.rt.keys()].map((key) => {
this.rt.set(key, Math.max(this.rt.get(key) ?? 0, set.rt.get(key) ?? 0));
});
}
}