MCPcopy Create free account
hub / github.com/MaterializeInc/demos / State

Class State

connection-examples/nodejs/state.js:1–73  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class State {
2 #state;
3 #timestamp;
4 #valid;
5 #history;
6
7 constructor(collectHistory) {
8 this.#state = new Map();
9 this.#timestamp = 0;
10 this.#valid = true;
11 if (collectHistory) {
12 this.#history = [];
13 }
14 }
15
16 getState() {
17 const list = new Array();
18
19 Array.from(this.#state.entries()).forEach(([key, value]) => {
20 const clone = JSON.parse(key);
21 let i = 0;
22 while (i< value) {
23 list.push(clone);
24 i++;
25 };
26 });
27
28 return list;
29 }
30
31 getHistory() {
32 return this.#history;
33 }
34
35 #validate(timestamp) {
36 if (!this.#valid) {
37 throw new Error("Invalid state.");
38 } else if (timestamp < this.#timestamp) {
39 console.error("Invalid timestamp.");
40 this.#valid = false;
41 throw new Error(
42 `Update with timestamp (${timestamp}) is lower than the last timestamp (${
43 this.#timestamp
44 }). Invalid state.`
45 );
46 }
47 }
48
49 #process({ value: _value, diff }) {
50 // Count value starts as a NaN
51 const value = JSON.stringify(_value);
52 const count = this.#state.has(value) ? (this.#state.get(value) + diff) : diff;
53
54 if (count <= 0) {
55 this.#state.delete(value);
56 } else {
57 this.#state.set(value, count);
58 }
59
60

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected