Skip to content

Commit c3c6cb1

Browse files
addaleaxMylesBorins
authored andcommitted
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: #14758 PR-URL: #14790 Reviewed-By: Refael Ackermann <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Evan Lucas <[email protected]> Reviewed-By: Timothy Gu <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Tobias Nießen <[email protected]> Reviewed-By: Yuta Hiroto <[email protected]> Reviewed-By: Alexey Orlenko <[email protected]> Reviewed-By: Ruben Bridgewater <[email protected]>
1 parent dcd7817 commit c3c6cb1

File tree

1 file changed

+15
-16
lines changed

1 file changed

+15
-16
lines changed

lib/util.js

+15-16
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)