Skip to content

Commit

Permalink
Merge pull request #10 from marcolink/feat/max-depth
Browse files Browse the repository at this point in the history
feat: add max depth config
  • Loading branch information
marcolink authored Sep 3, 2024
2 parents fe743f2 + 6c689b5 commit a787cd9
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
38 changes: 38 additions & 0 deletions src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,44 @@ describe('a generate json patch function', () => {
]);
});
});

describe('with maxDepth config', () => {
const before = {
firstLevel: {
secondLevel: {
thirdLevel: {
fourthLevel: 'hello-world',
},
thirdLevelTwo: 'hello',
},
},
};

const after = {
firstLevel: {
secondLevel: {
thirdLevel: {
fourthLevel: 'hello-brave-new-world',
},
thirdLevelTwo: 'hello',
},
},
};

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',
},
},
]);
});
});

function doPatch(json: JsonValue, patch: Patch) {
Expand Down
13 changes: 11 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ export type JsonPatchConfig = {
objectHash?: ObjectHash;
propertyFilter?: PropertyFilter;
array?: { ignoreMove?: boolean };
maxDepth?: number;
};

export const defaultObjectHash: ObjectHash = (obj, context) => {
Expand All @@ -82,7 +83,11 @@ export function generateJSONPatch(
after: JsonValue,
config: JsonPatchConfig = {}
): Patch {
const { objectHash = defaultObjectHash, propertyFilter } = config;
const {
objectHash = defaultObjectHash,
propertyFilter,
maxDepth = Infinity,
} = config;
const patch: Patch = [];
const hasPropertyFilter = typeof propertyFilter === 'function';

Expand Down Expand Up @@ -181,7 +186,11 @@ export function generateJSONPatch(
compareArrays(leftValue, rightValue, newPath);
} else if (isJsonObject(rightValue)) {
if (isJsonObject(leftValue)) {
compareObjects(newPath, leftValue, rightValue);
if (maxDepth <= path.split('/').length) {
patch.push({ op: 'replace', path: path, value: rightJsonValue });
} else {
compareObjects(newPath, leftValue, rightValue);
}
} else if (leftJsonValue.hasOwnProperty(rightKey)) {
patch.push({ op: 'replace', path: newPath, value: rightValue });
} else {
Expand Down

0 comments on commit a787cd9

Please sign in to comment.