-
Notifications
You must be signed in to change notification settings - Fork 0
/
counter.ts
executable file
·129 lines (109 loc) · 2.83 KB
/
counter.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import { randomString } from "../string";
import { Op, Id, OpType } from "./op";
//
// Operation-based counter
//
export class OBCounter {
value: number;
clientId: string;
clock: number;
ops: Op<number>[];
vector: Map<string, number>;
public constructor(init: number = 0, clientId?: string) {
this.value = init;
this.clientId = clientId ?? randomString(6);
this.clock = 0;
this.ops = [];
this.vector = new Map();
}
public get(): number {
return this.value;
}
public increment(): void {
this.value++;
this.ops.push({
type: OpType.Increment,
value: 1,
id: [this.clientId, this.clock++],
} as Op<number>);
}
public decrement(): void {
this.value--;
this.ops.push({
type: OpType.Decrement,
value: 1,
id: [this.clientId, this.clock++],
} as Op<number>);
}
public apply(op: Op<number>): void {
const id = op.id;
const clock = this.vector.get(id[0]) ?? -1;
// Ignore old ops
if (clock >= id[1]) {
return;
}
// New op must match clock sequence
if (clock + 1 !== id[1]) {
throw new Error(`Op id not in order: ${clock} ${id[1]}`);
}
if (op.type === OpType.Increment) {
this.value += op.value;
} else if (op.type === OpType.Decrement) {
this.value -= op.value;
} else {
throw new Error(`Unsupport op type: ${op.type}`);
}
this.vector.set(id[0], id[1]);
}
public ack(op: Op<number>): void {
this.ops = this.ops.filter((o) => !Id.equals(o.id, op.id));
}
public flush() {
return this.ops;
}
}
//
// State-based counter
//
export type CounterState = {
s1: Map<string, number>;
s2: Map<string, number>;
};
export class SBCounter {
clientId: string;
s1: Map<string, number>;
s2: Map<string, number>;
public constructor(clientId?: string) {
this.clientId = clientId ?? randomString(6);
this.s1 = new Map();
this.s2 = new Map();
}
public get(): number {
return (
Array.from(this.s1.values()).reduce((a, b) => a + b, 0) -
Array.from(this.s2.values()).reduce((a, b) => a + b, 0)
);
}
public increment(): void {
this.s1.set(this.clientId, (this.s1.get(this.clientId) ?? 0) + 1);
}
public decrement(): void {
this.s2.set(this.clientId, (this.s2.get(this.clientId) ?? 0) + 1);
}
public merge(other: CounterState): void {
for (const [k, v] of other.s1.entries()) {
const old = this.s1.get(k) ?? 0;
this.s1.set(k, Math.max(old, v));
}
for (const [k, v] of other.s2.entries()) {
const old = this.s2.get(k) ?? 0;
this.s2.set(k, Math.max(old, v));
}
}
public toState(): CounterState {
return {
s1: this.s1,
s2: this.s2,
};
}
}