-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.js
More file actions
92 lines (70 loc) · 1.89 KB
/
client.js
File metadata and controls
92 lines (70 loc) · 1.89 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const Operation = require('./operation');
const server = require('./server');
let nID = 0;
class Client {
constructor() {
this.id = ++nID;
this.buffer = [];
this.operationHistory = [];
this.state = [];
this.stateNoSync = [];
this.notYetSynchronizedOperations = [];
server.connectToServer(this);
}
inputOperation(op) {
op.setClient(this);
console.log(`Client${this.id} inputOperation: ${op}`);
op.applyOperation(this.state);
this.operationHistory.push(op);
this.operationNeedToBeSynchronized(op);
server.getBuffer().push(op.clone());
}
receive() {
const op = this.popFromBuffer();
if (op === null) {
return;
}
if (this.isSynchronized() === false && op.isSyncOperation()) {
this.operationSynchronized(op.getOriginalOperation());
op.doSync(this.state);
this.operationHistory.push(op);
return;
}
op.applyOperation(this.state);
this.operationHistory.push(op);
}
popFromBuffer() {
if (this.getBuffer().length === 0) {
return null;
}
return this.getBuffer().splice(0, 1)[0];
}
operationSynchronized(o) {
this.notYetSynchronizedOperations = this.notYetSynchronizedOperations.filter(item => item !== o);
}
operationNeedToBeSynchronized(o) {
this.notYetSynchronizedOperations.push(o);
}
isSynchronized() {
return this.notYetSynchronizedOperations.length === 0;
}
getBuffer() {
return this.buffer;
}
printState() {
console.log(`==== client${this.id}'s state: "${this.state.join('')}"`);
}
printOperationHistory() {
console.log(`=== client${this.id}'s operation history:`);
this.operationHistory.forEach(op => {
console.log(op.toString());
});
}
printBuffer() {
console.log(`==== client${this.id}'s buffer:`);
this.buffer.forEach(op => {
console.log(op.toString());
})
}
}
module.exports = Client;