57 lines
1.1 KiB
JavaScript
57 lines
1.1 KiB
JavaScript
import * as I from 'immutable';
|
|
|
|
import {nextStep} from './next-step';
|
|
|
|
export class Synchronizer {
|
|
|
|
constructor(statefuls) {
|
|
this._state = I.Map();
|
|
this._statefuls = statefuls;
|
|
this.updateState();
|
|
}
|
|
|
|
patchState(patch) {
|
|
const stepMap = {};
|
|
for (const step of patch) {
|
|
const [key, substep] = nextStep(step)
|
|
if (!stepMap[key]) {
|
|
stepMap[key] = [];
|
|
}
|
|
stepMap[key].push(substep);
|
|
}
|
|
for (const key in stepMap) {
|
|
const stateful = this._statefuls[key];
|
|
if (!stateful) {
|
|
continue;
|
|
}
|
|
stateful.patchState(stepMap[key]);
|
|
}
|
|
}
|
|
|
|
setStateful(key, stateful) {
|
|
this._statefuls[key] = stateful;
|
|
}
|
|
|
|
get state() {
|
|
return this._state;
|
|
}
|
|
|
|
tick(elapsed) {
|
|
for (const key in this._statefuls) {
|
|
const stateful = this._statefuls[key];
|
|
stateful.tick(elapsed);
|
|
}
|
|
this.updateState();
|
|
}
|
|
|
|
updateState() {
|
|
this._state = this._state.withMutations((state) => {
|
|
for (const key in this._statefuls) {
|
|
const stateful = this._statefuls[key];
|
|
state.set(key, stateful.state);
|
|
}
|
|
});
|
|
}
|
|
|
|
}
|