Skip to content

Commit a787cd9

Browse files
authored
Merge pull request #10 from marcolink/feat/max-depth
feat: add max depth config
2 parents fe743f2 + 6c689b5 commit a787cd9

File tree

2 files changed

+49
-2
lines changed

2 files changed

+49
-2
lines changed

src/index.spec.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -653,6 +653,44 @@ describe('a generate json patch function', () => {
653653
]);
654654
});
655655
});
656+
657+
describe('with maxDepth config', () => {
658+
const before = {
659+
firstLevel: {
660+
secondLevel: {
661+
thirdLevel: {
662+
fourthLevel: 'hello-world',
663+
},
664+
thirdLevelTwo: 'hello',
665+
},
666+
},
667+
};
668+
669+
const after = {
670+
firstLevel: {
671+
secondLevel: {
672+
thirdLevel: {
673+
fourthLevel: 'hello-brave-new-world',
674+
},
675+
thirdLevelTwo: 'hello',
676+
},
677+
},
678+
};
679+
680+
const patch = generateJSONPatch(before, after, { maxDepth: 3 });
681+
expect(patch).to.eql([
682+
{
683+
op: 'replace',
684+
path: '/firstLevel/secondLevel',
685+
value: {
686+
thirdLevel: {
687+
fourthLevel: 'hello-brave-new-world',
688+
},
689+
thirdLevelTwo: 'hello',
690+
},
691+
},
692+
]);
693+
});
656694
});
657695

658696
function doPatch(json: JsonValue, patch: Patch) {

src/index.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ export type JsonPatchConfig = {
7171
objectHash?: ObjectHash;
7272
propertyFilter?: PropertyFilter;
7373
array?: { ignoreMove?: boolean };
74+
maxDepth?: number;
7475
};
7576

7677
export const defaultObjectHash: ObjectHash = (obj, context) => {
@@ -82,7 +83,11 @@ export function generateJSONPatch(
8283
after: JsonValue,
8384
config: JsonPatchConfig = {}
8485
): Patch {
85-
const { objectHash = defaultObjectHash, propertyFilter } = config;
86+
const {
87+
objectHash = defaultObjectHash,
88+
propertyFilter,
89+
maxDepth = Infinity,
90+
} = config;
8691
const patch: Patch = [];
8792
const hasPropertyFilter = typeof propertyFilter === 'function';
8893

@@ -181,7 +186,11 @@ export function generateJSONPatch(
181186
compareArrays(leftValue, rightValue, newPath);
182187
} else if (isJsonObject(rightValue)) {
183188
if (isJsonObject(leftValue)) {
184-
compareObjects(newPath, leftValue, rightValue);
189+
if (maxDepth <= path.split('/').length) {
190+
patch.push({ op: 'replace', path: path, value: rightJsonValue });
191+
} else {
192+
compareObjects(newPath, leftValue, rightValue);
193+
}
185194
} else if (leftJsonValue.hasOwnProperty(rightKey)) {
186195
patch.push({ op: 'replace', path: newPath, value: rightValue });
187196
} else {

0 commit comments

Comments
 (0)