@syncable/core
Version:
57 lines • 2.1 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsondiffpatch_1 = require("jsondiffpatch");
const lodash_1 = tslib_1.__importDefault(require("lodash"));
const diffPatcher = new jsondiffpatch_1.DiffPatcher({
objectHash(object, index) {
return object.id || object._id || object.key || `$$index:${index}`;
},
cloneDiffValues: true,
});
function diff(left, right) {
let delta = diffPatcher.diff(left, right);
// Package jsondiffpatch keeps the old value for operations like reverse /
// unpatch. And in our case we don't need them so removing them will make the
// updates more compact.
return (delta &&
lodash_1.default.cloneDeepWith(delta, value => {
if (Array.isArray(value)) {
switch (value.length) {
case 1:
// new value
return value;
case 2:
// replaced value
return [0, value[1]];
// ^ old value replaced with placeholder 0
case 3: {
switch (value[2]) {
case 0:
// delete
// value[1] should also be 0
return [0, 0, 0];
// ^ old value replaced with placeholder 0
case 2:
// text diffs
case 3:
// array moves
default:
return value;
}
}
default:
return value;
}
}
else {
return undefined;
}
}));
}
exports.diff = diff;
function patch(left, delta) {
diffPatcher.patch(left, delta);
}
exports.patch = patch;
//# sourceMappingURL=diff-patcher.js.map