-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1-counter.js
More file actions
67 lines (54 loc) · 1.1 KB
/
1-counter.js
File metadata and controls
67 lines (54 loc) · 1.1 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
'use strict';
class Counter {
#id;
#seq = 0;
#ops = [];
#applied = new Set();
constructor(id) {
this.#id = id;
}
inc(x = 1) {
this.#update(x);
}
dec(x = 1) {
this.#update(-x);
}
#update(delta) {
const id = `${this.#id}:${this.#seq++}`;
this.#ops.push({ id, delta });
this.#applied.add(id);
}
merge(ops) {
for (const op of ops) {
if (!this.#applied.has(op.id)) {
this.#ops.push(op);
this.#applied.add(op.opId);
}
}
}
get value() {
return this.#ops.reduce((sum, { delta }) => sum + delta, 0);
}
get operations() {
return this.#ops;
}
}
// Usage
console.log('Replica 0');
const counter0 = new Counter(0);
counter0.inc(4);
counter0.inc();
counter0.dec();
console.log(counter0.operations);
console.log('Replica 1');
const counter1 = new Counter(1);
counter1.dec(5);
counter1.inc();
counter1.inc(3);
console.log(counter1.operations);
console.log('Sync');
counter1.merge(counter0.operations);
counter0.merge(counter1.operations);
console.log(counter0.operations);
console.log('Get value');
console.log(counter0.value);