import * as I from 'immutable'; export class StateSynchronizer { constructor(statefuls) { this._state = I.Map(); this._statefuls = statefuls; this.tick(); } static nextStep(step) { const {path, op, value} = step; const parts = path.split('/'); const [key] = parts.splice(1, 1); const subpath = parts.join('/'); return [key, { op, path: subpath ? subpath : '/', value, }]; } patchState(patch) { const stepMap = {}; for (const {op, path, value} of patch) { const parts = path.split('/'); const [key] = parts.splice(1, 1); if (!stepMap[key]) { stepMap[key] = []; } const subpath = parts.join('/'); stepMap[key].push({ op, path: subpath ? subpath : '/', value, }); } for (const key in stepMap) { const stateful = this._statefuls[key]; if (!stateful) { continue; } stateful.patchState(stepMap[key]); } } get state() { return this._state; } tick() { for (const key in this._statefuls) { const stateful = this._statefuls[key]; this._state = this._state.set(key, stateful.state); } } }