Skip to content

Commit a04fd16

Browse files
util: use proper circular reference checking
Circular references are conceptually nothing that should be checked for objects (or Sets or Maps) only, but applies to recursive structures in general, so move the `seen` checks into a position where it is part of the recursion itself. Fixes: #1 PR-URL: #2
1 parent 491cc76 commit a04fd16

File tree

1 file changed

+15
-16
lines changed

1 file changed

+15
-16
lines changed

lib/util.js

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -612,10 +612,13 @@ function formatValue(ctx, value, recurseTimes) {
612612
}
613613
}
614614

615-
ctx.seen.push(value);
616-
617-
var output = formatter(ctx, value, recurseTimes, visibleKeys, keys);
615+
// TODO(addaleax): Make `seen` a Set to avoid linear-time lookup.
616+
if (ctx.seen.includes(value)) {
617+
return ctx.stylize('[Circular]', 'special');
618+
}
618619

620+
ctx.seen.push(value);
621+
const output = formatter(ctx, value, recurseTimes, visibleKeys, keys);
619622
ctx.seen.pop();
620623

621624
return reduceToSingleString(output, base, braces, ctx.breakLength);
@@ -835,21 +838,17 @@ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
835838
}
836839
}
837840
if (!str) {
838-
if (ctx.seen.indexOf(desc.value) < 0) {
839-
if (recurseTimes === null) {
840-
str = formatValue(ctx, desc.value, null);
841+
if (recurseTimes === null) {
842+
str = formatValue(ctx, desc.value, null);
843+
} else {
844+
str = formatValue(ctx, desc.value, recurseTimes - 1);
845+
}
846+
if (str.indexOf('\n') > -1) {
847+
if (array) {
848+
str = str.replace(/\n/g, '\n ');
841849
} else {
842-
str = formatValue(ctx, desc.value, recurseTimes - 1);
843-
}
844-
if (str.indexOf('\n') > -1) {
845-
if (array) {
846-
str = str.replace(/\n/g, '\n ');
847-
} else {
848-
str = str.replace(/^|\n/g, '\n ');
849-
}
850+
str = str.replace(/^|\n/g, '\n ');
850851
}
851-
} else {
852-
str = ctx.stylize('[Circular]', 'special');
853852
}
854853
}
855854
if (name === undefined) {

0 commit comments

Comments
 (0)