avocado-old/packages/state/packer.js

54 lines
945 B
JavaScript
Raw Normal View History

2019-04-05 22:40:04 -05:00
export class Packer {
constructor() {
this._keyCaret = 0;
this._keys = {};
}
pack(steps) {
const newKeys = {};
const packedSteps = steps.map((step) => {
const {op, path, value} = step;
if (!this._keys[path]) {
this._keys[path] = newKeys[path] = this._keyCaret++;
}
return {
op,
path: this._keys[path],
value,
}
});
const payload = {
steps: packedSteps,
};
if (0 !== Object.keys(newKeys).length) {
payload.newKeys = newKeys;
}
return payload;
}
}
export class Unpacker {
constructor() {
this._keys = {};
}
unpack(payload) {
const {newKeys, steps} = payload;
for (const key in newKeys) {
this._keys[newKeys[key]] = key;
}
return steps.map((step) => {
const {op, path, value} = step;
return {
op,
path: this._keys[path],
value,
};
});
}
}