UNPKG

datum-merge

Version:

Simplified diff and merging for deeply nested objects

80 lines (79 loc) 2.98 kB
import { get, set, toPath, unset } from "lodash-es"; import { deepDiffLow } from "./diff-high"; export function diffToPatchLog(differences, storePrev = false) { var _a, _b, _c; const jsonPatch = []; for (const dif of differences) { let pointer = asJsonPointer((_a = dif.path) !== null && _a !== void 0 ? _a : []); switch (dif.kind) { case "N": jsonPatch.push({ op: "add", path: pointer, value: dif.rhs }); break; case "E": jsonPatch.push({ op: "replace", path: pointer, value: dif.rhs, prev: dif.lhs }); break; case "D": jsonPatch.push({ op: "remove", path: pointer, prev: dif.lhs }); break; case "A": pointer = `${pointer}/${dif.index}`; if (((_b = dif.item) === null || _b === void 0 ? void 0 : _b.kind) === 'N') { jsonPatch.push({ op: "add", path: pointer, value: dif.item.rhs }); } if (((_c = dif.item) === null || _c === void 0 ? void 0 : _c.kind) === 'D') { jsonPatch.push({ op: "remove", path: pointer, prev: dif.item.lhs }); } break; } } if (!storePrev) { jsonPatch.forEach((p) => delete p.prev); } return jsonPatch; } export function applyPatchLog(patchLog, target = {}) { if (!patchLog) return target; for (const patchItem of patchLog) { const difPath = asLodashPath(patchItem.path); if (patchItem.op === "remove") { unset(target, difPath); } else { set(target, difPath, patchItem.value); } } return target; } export function deepPatchLog(lhsObj, rhsObj, orderInd = false, storePrev = false) { const differences = deepDiffLow(lhsObj, rhsObj, orderInd); return !differences ? [] : diffToPatchLog(differences, storePrev); } ; function escapePathPart(path) { if (typeof path === 'number') return path.toString(); if (typeof path === 'symbol') return path.toString(); if (path.indexOf('/') === -1 && path.indexOf('~') === -1) return path; return path.replace(/~/g, '~0').replace(/\//g, '~1'); } function unescapePathPart(path) { return path.replace(/~1/g, '/').replace(/~0/g, '~'); } function asJsonPointer(path) { return !(path === null || path === void 0 ? void 0 : path.length) ? "" : "/" + path.map((s) => escapePathPart(s)).join("/"); } export function asLodashPath(pointer) { if (!pointer || !pointer.startsWith("/")) return []; const parts = pointer.slice(1).split("/") .map((s) => unescapePathPart(s)); return !(parts === null || parts === void 0 ? void 0 : parts.length) ? [] : toPath(parts.join(".")); } export function getValueByPointer(document, pointer) { return pointer === "" ? document : get(document, asLodashPath(pointer)); }