Skip to content

Commit

Permalink
util: fix circular ref for Set and Map
Browse files Browse the repository at this point in the history
  • Loading branch information
BridgeAR committed Aug 11, 2017
1 parent 7307839 commit be7195c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
12 changes: 9 additions & 3 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -738,7 +738,9 @@ function formatSet(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
value.forEach(function(v) {
var nextRecurseTimes = recurseTimes === null ? null : recurseTimes - 1;
var str = formatValue(ctx, v, nextRecurseTimes);
var str = ctx.seen.includes(v) ?
ctx.stylize('[Circular]', 'special') :
formatValue(ctx, v, nextRecurseTimes);
output.push(str);
});
for (var n = 0; n < keys.length; n++) {
Expand All @@ -753,9 +755,13 @@ function formatMap(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
value.forEach(function(v, k) {
var nextRecurseTimes = recurseTimes === null ? null : recurseTimes - 1;
var str = formatValue(ctx, k, nextRecurseTimes);
var str = ctx.seen.includes(k) ?
ctx.stylize('[Circular]', 'special') :
formatValue(ctx, k, nextRecurseTimes);
str += ' => ';
str += formatValue(ctx, v, nextRecurseTimes);
str += ctx.seen.includes(v) ?
ctx.stylize('[Circular]', 'special') :
formatValue(ctx, v, nextRecurseTimes);
output.push(str);
});
for (var n = 0; n < keys.length; n++) {
Expand Down
19 changes: 19 additions & 0 deletions test/parallel/test-util-inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -783,6 +783,13 @@ if (typeof Symbol !== 'undefined') {
);
}

// Test circular Set
{
const set = new Set();
set.add(set);
assert.strictEqual(util.inspect(set), 'Set { [Circular] }');
}

// test Map
{
assert.strictEqual(util.inspect(new Map()), 'Map {}');
Expand All @@ -794,6 +801,18 @@ if (typeof Symbol !== 'undefined') {
'Map { \'foo\' => null, [size]: 1, bar: 42 }');
}

// Test circular Map
{
const map = new Map();
map.set(map, 'map');
assert.strictEqual(util.inspect(map), "Map { [Circular] => 'map' }");
map.set(map, map);
assert.strictEqual(util.inspect(map), 'Map { [Circular] => [Circular] }');
map.delete(map);
map.set('map', map);
assert.strictEqual(util.inspect(map), "Map { 'map' => [Circular] }");
}

// test Promise
{
const resolved = Promise.resolve(3);
Expand Down

0 comments on commit be7195c

Please sign in to comment.