refactor: elegance

This commit is contained in:
cha0s 2019-04-05 16:08:59 -04:00
parent 220ceac711
commit e7c6cb8556

View File

@ -20,46 +20,39 @@ export class StateSynchronizer {
}
diff(previousState) {
const state = this._state;
const diff = {};
for (const key in this._statefuls) {
if (previousState.get(key) !== state.get(key)) {
diff[key] = this.diffStateful(
previousState.get(key),
state.get(key)
);
}
}
return diff;
// Take a pure JS diff.
const steps = immutablediff(previousState, this._state).toJS();
const updateSteps = steps.filter(StateSynchronizer.isStepUpdate);
return StateSynchronizer.hydratePathValues(updateSteps);
}
diffStateful(previous, current) {
// Take a pure JS diff.
const steps = immutablediff(previous, current).toJS();
let diff = {};
for (const {op, path, value} of steps) {
if ('replace' === op || 'add' === op) {
if ('/' === path) {
diff = value;
}
else {
const parts = path.split('/');
parts.shift();
let walk = diff;
for (let i = 0; i < parts.length; ++i) {
const part = parts[i];
walk[part] = walk[part] || {};
if (i === parts.length - 1) {
walk[part] = value;
}
else {
walk = walk[part];
}
static hydratePathValues(pathValues) {
let accumulated = {};
for (const {path, value} of pathValues) {
if ('/' === path) {
accumulated = value;
}
else {
const parts = path.split('/');
parts.shift();
let walk = accumulated;
for (let i = 0; i < parts.length; ++i) {
const part = parts[i];
walk[part] = walk[part] || {};
if (i === parts.length - 1) {
walk[part] = value;
}
else {
walk = walk[part];
}
}
}
}
return diff;
return accumulated;
}
static isStepUpdate(step) {
return -1 !== ['add', 'replace'].indexOf(step.op);
}
get state() {