avocado-old/packages/state/synchronizer.js

59 lines
1.2 KiB
JavaScript
Raw Normal View History

2019-03-20 18:33:13 -05:00
import * as I from 'immutable';
export class StateSynchronizer {
constructor(statefuls) {
this._state = I.Map();
this._statefuls = statefuls;
this.tick();
2019-03-20 18:33:13 -05:00
}
2019-04-07 11:43:50 -05:00
static nextStep(step) {
2019-04-05 22:14:29 -05:00
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,
}];
2019-04-05 15:08:59 -05:00
}
2019-04-05 15:16:55 -05:00
patchState(patch) {
2019-04-05 22:14:29 -05:00
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) {
2019-04-05 15:16:55 -05:00
const stateful = this._statefuls[key];
if (!stateful) {
continue;
}
2019-04-05 22:14:29 -05:00
stateful.patchState(stepMap[key]);
2019-04-05 15:16:55 -05:00
}
}
get state() {
2019-03-20 18:33:13 -05:00
return this._state;
}
tick() {
2019-03-20 18:33:13 -05:00
for (const key in this._statefuls) {
const stateful = this._statefuls[key];
2019-03-26 15:41:49 -05:00
this._state = this._state.set(key, stateful.state);
2019-03-20 18:33:13 -05:00
}
}
}