-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstate.js
More file actions
75 lines (63 loc) · 1.64 KB
/
Copy pathstate.js
File metadata and controls
75 lines (63 loc) · 1.64 KB
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
class State {
#state;
#timestamp;
#valid;
#history;
constructor(collectHistory) {
this.#state = new Map();
this.#timestamp = 0;
this.#valid = true;
if (collectHistory) {
this.#history = [];
}
}
getState() {
const list = new Array();
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() {
return this.#history;
}
#validate(timestamp) {
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.`
);
}
}
#process({ value: _value, diff }) {
// Count value starts as a NaN
const value = JSON.stringify(_value);
const count = this.#state.has(value) ? (this.#state.get(value) + 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, timestamp) {
if (updates.length > 0) {
this.#validate(timestamp);
this.#timestamp = timestamp;
updates.forEach(this.#process.bind(this));
}
}
};
module.exports = State;