-
Notifications
You must be signed in to change notification settings - Fork 3
/
state.ts
78 lines (66 loc) · 1.78 KB
/
state.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
export interface Update<T> {
value: T;
diff: number;
}
export default class State<T> {
private state: Map<string, number>;
private timestamp: number;
private valid: boolean;
private history: Array<Update<T>> | undefined;
constructor(collectHistory?: boolean) {
this.state = new Map();
this.timestamp = 0;
this.valid = true;
if (collectHistory) {
this.history = [];
}
}
getState(): Readonly<Array<T>> {
const list: Array<T> = new Array<T>();
Array.from(this.state.entries()).forEach(([key, value]) => {
const clone = JSON.parse(key);
let i = 0;
while (i< value) {
list.push(clone);
i++;
};
});
return list;
}
getHistory(): Array<Update<T>> | undefined {
return this.history;
}
private validate(timestamp: number) {
if (!this.valid) {
throw new Error("Invalid state.");
} else if (timestamp < this.timestamp) {
console.error("Invalid timestamp.");
this.valid = false;
throw new Error(
`Update with timestamp (${timestamp}) is lower than the last timestamp (${
this.timestamp
}). Invalid state.`
);
}
}
private process({ value: _value, diff }: Update<T>) {
// Count value starts as a NaN
const value = JSON.stringify(_value);
const count = this.state.has(value) ? (this.state.get(value) as number + diff) : diff;
if (count <= 0) {
this.state.delete(value);
} else {
this.state.set(value, count);
}
if (this.history) {
this.history.push({ value: _value, diff });
}
}
update(updates: Array<Update<T>>, timestamp: number) {
if (updates.length > 0) {
this.validate(timestamp);
this.timestamp = timestamp;
updates.forEach(this.process.bind(this));
}
}
};