From 25833a5b60aee08b1590e1eb86b2d5d2391e6563 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Wed, 16 Aug 2017 21:21:29 -0300 Subject: [PATCH] util: fix inspect array w. negative maxArrayLength MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/14880 Reviewed-By: Timothy Gu Reviewed-By: Alexey Orlenko Reviewed-By: James M Snell Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Tobias Nießen --- lib/util.js | 7 ++++--- test/parallel/test-util-inspect.js | 4 ++++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/lib/util.js b/lib/util.js index 94d7b828bd2845..b1225365d365c3 100644 --- a/lib/util.js +++ b/lib/util.js @@ -682,11 +682,12 @@ function formatObject(ctx, value, recurseTimes, visibleKeys, keys) { function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + const maxLength = Math.min(Math.max(0, ctx.maxArrayLength), value.length); var output = []; let visibleLength = 0; let index = 0; for (const elem of keys) { - if (visibleLength === ctx.maxArrayLength) + if (visibleLength === maxLength) break; // Symbols might have been added to the keys if (typeof elem !== 'string') @@ -701,7 +702,7 @@ function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { const message = `<${emptyItems} empty item${ending}>`; output.push(ctx.stylize(message, 'undefined')); index = i; - if (++visibleLength === ctx.maxArrayLength) + if (++visibleLength === maxLength) break; } output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, @@ -709,7 +710,7 @@ function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { visibleLength++; index++; } - if (index < value.length && visibleLength !== ctx.maxArrayLength) { + if (index < value.length && visibleLength !== maxLength) { const len = value.length - index; const ending = len > 1 ? 's' : ''; const message = `<${len} empty item${ending}>`; diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index 8cbd6a36227f0f..42717ee79dc84c 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -970,6 +970,10 @@ if (typeof Symbol !== 'undefined') { { const x = new Array(101).fill(); assert(!util.inspect(x, { maxArrayLength: 101 }).endsWith('1 more item ]')); + assert.strictEqual( + util.inspect(x, { maxArrayLength: -1 }), + '[ ... 101 more items ]' + ); } {