Skip to content

Commit

Permalink
Add explanation comments for circular structure detection and improve…
Browse files Browse the repository at this point in the history
… tests
  • Loading branch information
david0xd committed Jul 12, 2022
1 parent 44db981 commit d1e06bb
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
11 changes: 10 additions & 1 deletion src/json.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -778,7 +778,8 @@ describe('json', () => {
]);
});

it('should return true for validity for an object that contains same object multiple times', () => {
it('should return true for validity for an object that contains the same object multiple times', () => {
// This will test if false positives are removed from the circular reference detection
const date = new Date();
const testObject = {
value: 'whatever',
Expand Down Expand Up @@ -806,6 +807,14 @@ describe('json', () => {
something: null,
somethingElse: null,
anotherValue: null,
somethingAgain: testObject,
anotherOne: {
nested: {
multipleTimes: {
valueOne: testObject,
},
},
},
},
};

Expand Down
10 changes: 9 additions & 1 deletion src/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -355,10 +355,13 @@ export function validateJsonAndGetSize(
return [false, 0];
}

// Handle circular objects
// Circular object detection (handling)
// Check if the same object already exists
if (seenObjects.has(value)) {
return [false, 0];
}
// Add new object to the seen objects set
// Only the plain objects should be added (Primitive types are skipped)
seenObjects.add(value);

// Continue object decomposition
Expand All @@ -378,7 +381,12 @@ export function validateJsonAndGetSize(
'JSON validation did not pass. Validation process stopped.',
);
}

// Circular object detection
// Once a child node is visited and processed remove it from the set.
// This will prevent false positives with the same adjacent objects.
seenObjects.delete(value);

if (skipSizing) {
return 0;
}
Expand Down

0 comments on commit d1e06bb

Please sign in to comment.