54 lines
945 B
JavaScript
54 lines
945 B
JavaScript
|
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,
|
||
|
};
|
||
|
});
|
||
|
}
|
||
|
|
||
|
}
|