-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
73 lines (58 loc) · 1.39 KB
/
server.js
File metadata and controls
73 lines (58 loc) · 1.39 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
const Operation = require('./operation');
const OperationFactory = require('./operation-factory');
class Server {
constructor() {
this.operationHistory = [];
this.buffer = [];
this.clients = [];
this.state = [];
}
receive() {
const op = this.popFromBuffer();
if (op === null) {
return;
}
op.applyOperation(this.state);
this.operationHistory.push(op);
op.checkState(this.state);
this.send(op);
}
send(op) {
this.clients.forEach(client => {
if (client === op.getClient()) {
const syncOp = OperationFactory.createSyncOperation(op);
client.getBuffer().push(syncOp);
} else {
client.getBuffer().push(op.clone());
}
});
}
popFromBuffer() {
if (this.getBuffer().length === 0) {
return null;
}
return this.getBuffer().splice(0, 1)[0];
}
connectToServer(client) {
this.clients.push(client);
}
getBuffer() {
return this.buffer;
}
printState() {
console.log(`==== server's state: "${this.state.join('')}"`);
}
printBuffer() {
console.log('==== server\'s buffer:');
this.getBuffer().forEach(op => {
console.log(` ${op.toString()}`);
})
}
printOperationHistory() {
console.log(`==== server\'s operation history:`);
this.operationHistory.forEach(op => {
console.log(op.toString());
});
}
}
module.exports = new Server();