From be7195c59cc2eaba4ba322ccbdf3264d988a4253 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Fri, 11 Aug 2017 14:30:37 -0300 Subject: [PATCH] util: fix circular ref for Set and Map Fixes #14758 --- lib/util.js | 12 +++++++++--- test/parallel/test-util-inspect.js | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/lib/util.js b/lib/util.js index a9f267bd416ddc..38bd8dd7daa105 100644 --- a/lib/util.js +++ b/lib/util.js @@ -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++) { @@ -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++) { diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index df9e3d7f7def4d..7e25331efd986e 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -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 {}'); @@ -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);