Skip to content

Commit

Permalink
Fix #1 - make circular reference only when the result of toJSON is no…
Browse files Browse the repository at this point in the history
…t a primitive
  • Loading branch information
mjbrisebois committed Mar 16, 2022
1 parent 7194fd4 commit 84351e1
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ function toReadableString ( value, indent, replacer ) {
"indent": 4,
"truncate_views": 50,
};
if ( typeof indent === "object" && indent !== null )
if ( is_object(indent) )
options = Object.assign( options, indent );
else if ( indent !== undefined )
options.indent = indent;
Expand All @@ -218,8 +218,6 @@ function toReadableString ( value, indent, replacer ) {
return `${RAW_PREFIX}[Circular reference to #/${seen.get(v).join('/')}]`;

if ( is_object(v) ) {
seen.set( v, path ); // Add value before copy

try {
v = v.toJSON( k );
} catch (err) {
Expand All @@ -228,6 +226,8 @@ function toReadableString ( value, indent, replacer ) {
|| err.message.includes("Cannot read property 'toJSON'"))) )
throw err;
}
if ( is_object(v) )
seen.set( v, path ); // Add value after toJSON but before copy

if ( v.constructor.name === "Object" )
v = Object.assign({}, v);
Expand Down
22 changes: 22 additions & 0 deletions tests/unit/test_debug.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,28 @@ function basic_tests () {
).to.equal(`{"a":9007199254740991n,"b":9007199254740991n}`);
}
});

it("should not circular reference primitive values", async () => {
class Something {
toJSON () {
return "primitive value";
}
}
const eventual_primitive = new Something();

const input = {
"eventual_primitive": eventual_primitive,
"sublevel": {
"list": [
eventual_primitive,
],
"eventual_primitive": eventual_primitive,
}
};
let text = debug( input );

expect( text ).to.equal( JSON.stringify(input, null, 4) );
});
}

describe("Debug", () => {
Expand Down

0 comments on commit 84351e1

Please sign in to comment.