-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path2-pn-counter.js
More file actions
71 lines (58 loc) · 1.74 KB
/
2-pn-counter.js
File metadata and controls
71 lines (58 loc) · 1.74 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
'use strict';
class PNCounter {
#id;
#pc;
#nc;
constructor(id, options = {}) {
this.#id = id;
const { pCounts, nCounts, size = 1 } = options;
if (id >= size) throw new Error(`Invalid id: ${id}, max: ${size - 1}`);
this.#pc = pCounts ? structuredClone(pCounts) : new Array(size).fill(0);
this.#nc = nCounts ? structuredClone(nCounts) : new Array(size).fill(0);
}
inc(x = 1) {
if (x < 0) throw new Error('Negative increment is not allowed');
this.#pc[this.#id] += x;
}
dec(x = 1) {
if (x < 0) throw new Error('Negative decrement is not allowed');
this.#nc[this.#id] += x;
}
merge({ pCounts, nCounts }) {
const size = pCounts.length;
if (size !== nCounts.length) throw new Error('Wrong data size');
for (let id = 0; id < size; id++) {
this.#pc[id] = Math.max(this.#pc[id], pCounts[id]);
this.#nc[id] = Math.max(this.#nc[id], nCounts[id]);
}
}
get value() {
const pSum = this.#pc.reduce((sum, cur) => sum + cur, 0);
const nSum = this.#nc.reduce((sum, cur) => sum + cur, 0);
return pSum - nSum;
}
get counts() {
return { pCounts: this.#pc, nCounts: this.#nc };
}
}
// Usage
const size = 2;
console.log('Replica 0');
const counter0 = new PNCounter(0, { size });
counter0.inc();
counter0.inc(2);
counter0.dec(5);
console.log({ id0: counter0.counts });
console.log('Replica 1');
const counter1 = new PNCounter(1, { size });
counter1.dec();
counter1.inc(7);
console.log({ id1: counter1.counts });
console.log('Sync');
counter1.merge(counter0.counts);
counter0.merge(counter1.counts);
console.log({ id0: counter0.counts });
console.log({ id1: counter1.counts });
console.log('Get value');
console.log({ id0: counter0.value });
console.log({ id1: counter1.value });