From 196c157a302d4318a4ec63a010eb7fc946dd0032 Mon Sep 17 00:00:00 2001 From: Marco Link Date: Tue, 3 Sep 2024 21:08:12 +0200 Subject: [PATCH] fix: maxDepth was not respected fully --- src/index.spec.ts | 35 +++++++++++++++++++++++++---------- src/index.ts | 4 ++-- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/src/index.spec.ts b/src/index.spec.ts index 13fb91b..7d69d97 100644 --- a/src/index.spec.ts +++ b/src/index.spec.ts @@ -677,19 +677,34 @@ describe('a generate json patch function', () => { }, }; - const patch = generateJSONPatch(before, after, { maxDepth: 3 }); - expect(patch).to.eql([ - { - op: 'replace', - path: '/firstLevel/secondLevel', - value: { - thirdLevel: { + it('detects changes as a given depth of 3', () => { + const patch = generateJSONPatch(before, after, { maxDepth: 3 }); + expect(patch).to.eql([ + { + op: 'replace', + path: '/firstLevel/secondLevel', + value: { + thirdLevel: { + fourthLevel: 'hello-brave-new-world', + }, + thirdLevelTwo: 'hello', + }, + }, + ]); + }); + + it('detects changes as a given depth of 4', () => { + const patch = generateJSONPatch(before, after, { maxDepth: 4 }); + expect(patch).to.eql([ + { + op: 'replace', + path: '/firstLevel/secondLevel/thirdLevel', + value: { fourthLevel: 'hello-brave-new-world', }, - thirdLevelTwo: 'hello', }, - }, - ]); + ]); + }); }); }); diff --git a/src/index.ts b/src/index.ts index da52d65..3765314 100644 --- a/src/index.ts +++ b/src/index.ts @@ -186,8 +186,8 @@ export function generateJSONPatch( compareArrays(leftValue, rightValue, newPath); } else if (isJsonObject(rightValue)) { if (isJsonObject(leftValue)) { - if (maxDepth <= path.split('/').length) { - patch.push({ op: 'replace', path: path, value: rightJsonValue }); + if (maxDepth <= newPath.split('/').length) { + patch.push({ op: 'replace', path: newPath, value: rightValue }); } else { compareObjects(newPath, leftValue, rightValue); }