@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
38 lines (35 loc) • 1.47 kB
JavaScript
import { JSONPointer } from '../../../enum.mjs';
import { getValue } from '../../manipulator/getValue.mjs';
import { setValue } from '../../manipulator/setValue.mjs';
import { compare } from '../compare/compare.mjs';
import { Operation } from '../type.mjs';
import { getArrayBasePath } from './utils/getArrayBasePath.mjs';
const differenceObjectPatch = (source, target) => {
const patches = 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(patch.path);
if (arrayPath === null)
validPatches.push(patch);
else if (!processedArrayPaths.has(arrayPath)) {
const segments = arrayPath.split(JSONPointer.Separator);
setValue(mergePatch, segments, getValue(target, segments));
processedArrayPaths.add(arrayPath);
}
}
for (let i = 0, l = validPatches.length; i < l; i++) {
const patch = validPatches[i];
if (patch.op === Operation.ADD || patch.op === Operation.REPLACE)
setValue(mergePatch, patch.path, patch.value);
else if (patch.op === Operation.REMOVE)
setValue(mergePatch, patch.path, null);
}
return mergePatch;
};
export { differenceObjectPatch };