@winglet/json
Version:
TypeScript library for safe and efficient JSON data manipulation with RFC 6901 (JSON Pointer) and RFC 6902 (JSON Patch) compliance, featuring prototype pollution protection and immutable operations
40 lines (36 loc) • 1.57 kB
JavaScript
;
var _enum = require('../../../enum.cjs');
var getValue = require('../../manipulator/getValue.cjs');
var setValue = require('../../manipulator/setValue.cjs');
var compare = require('../compare/compare.cjs');
var type = require('../type.cjs');
var getArrayBasePath = require('./utils/getArrayBasePath.cjs');
const differenceObjectPatch = (source, target) => {
const patches = compare.compare(source, target);
const patchCount = patches.length;
if (patchCount === 0)
return undefined;
const mergePatch = {};
const processedArrayPaths = new Set();
const validPatches = [];
for (let i = 0; i < patchCount; i++) {
const patch = patches[i];
const arrayPath = getArrayBasePath.getArrayBasePath(patch.path);
if (arrayPath === null)
validPatches.push(patch);
else if (!processedArrayPaths.has(arrayPath)) {
const segments = arrayPath.split(_enum.JSONPointer.Separator);
setValue.setValue(mergePatch, segments, getValue.getValue(target, segments));
processedArrayPaths.add(arrayPath);
}
}
for (let i = 0, l = validPatches.length; i < l; i++) {
const patch = validPatches[i];
if (patch.op === type.Operation.ADD || patch.op === type.Operation.REPLACE)
setValue.setValue(mergePatch, patch.path, patch.value);
else if (patch.op === type.Operation.REMOVE)
setValue.setValue(mergePatch, patch.path, null);
}
return mergePatch;
};
exports.differenceObjectPatch = differenceObjectPatch;