74 lines
2.0 KiB
JavaScript
74 lines
2.0 KiB
JavaScript
import {idFrom} from './registrar';
|
|
|
|
import SynchronizedCreatePacket from './synchronized-create.packet';
|
|
import SynchronizedDestroyPacket from './synchronized-destroy.packet';
|
|
|
|
export class ServerSynchronizer {
|
|
|
|
constructor() {
|
|
this._added = [];
|
|
this._removed = [];
|
|
this._synchronized = {};
|
|
this._synchronizedFlat = [];
|
|
}
|
|
|
|
addSynchronized(synchronized) {
|
|
if (this.hasSynchronized(synchronized)) {
|
|
return;
|
|
}
|
|
else {
|
|
this._added.push(synchronized);
|
|
}
|
|
const type = idFrom(synchronized.constructor);
|
|
if (!(type in this._synchronized)) {
|
|
this._synchronized[type] = new Map();
|
|
}
|
|
this._synchronizedFlat.push(synchronized);
|
|
const synchronizationId = synchronized.synchronizationId();
|
|
this._synchronized[type].set(synchronizationId, synchronized);
|
|
}
|
|
|
|
destroy() {}
|
|
|
|
hasSynchronized(synchronized) {
|
|
return -1 !== this._synchronizedFlat.indexOf(synchronized);
|
|
}
|
|
|
|
removeSynchronized(synchronized) {
|
|
if (!this.hasSynchronized(synchronized)) {
|
|
return;
|
|
}
|
|
else {
|
|
this._removed.push(synchronized);
|
|
}
|
|
const index = this._synchronizedFlat.indexOf(synchronized);
|
|
this._synchronizedFlat.splice(index, 1);
|
|
const type = idFrom(synchronized.constructor);
|
|
const synchronizationId = synchronized.synchronizationId();
|
|
this._synchronized[type].delete(synchronizationId);
|
|
}
|
|
|
|
packetsFor(informed) {
|
|
const payload = [];
|
|
for (let i = 0; i < this._synchronizedFlat.length; i++) {
|
|
const synchronized = this._synchronizedFlat[i];
|
|
if (-1 !== this._added.indexOf(synchronized)) {
|
|
payload.push(synchronized.createPacket(informed));
|
|
}
|
|
else if (-1 !== this._removed.indexOf(synchronized)) {
|
|
payload.push(synchronized.destroyPacket(informed));
|
|
}
|
|
else {
|
|
const packets = synchronized.packetsFor(informed);
|
|
for (let j = 0; j < packets.length; j++) {
|
|
payload.push(packets[j]);
|
|
}
|
|
}
|
|
}
|
|
this._added = [];
|
|
this._removed = [];
|
|
return payload;
|
|
}
|
|
|
|
}
|