@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.51 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 index = 0; index < patchCount; index++) {
const patch = patches[index];
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 index = 0, length = validPatches.length; index < length; index++) {
const patch = validPatches[index];
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 };