Skip to content

Commit de10c0f

Browse files
BridgeARMylesBorins
authored andcommitted
util: fix inspect array w. negative maxArrayLength
PR-URL: #14880 Reviewed-By: Timothy Gu <[email protected]> Reviewed-By: Alexey Orlenko <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Tobias Nießen <[email protected]>
1 parent 8f61bf2 commit de10c0f

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

lib/util.js

+4-3
Original file line numberDiff line numberDiff line change
@@ -682,11 +682,12 @@ function formatObject(ctx, value, recurseTimes, visibleKeys, keys) {
682682

683683

684684
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
685+
const maxLength = Math.min(Math.max(0, ctx.maxArrayLength), value.length);
685686
var output = [];
686687
let visibleLength = 0;
687688
let index = 0;
688689
for (const elem of keys) {
689-
if (visibleLength === ctx.maxArrayLength)
690+
if (visibleLength === maxLength)
690691
break;
691692
// Symbols might have been added to the keys
692693
if (typeof elem !== 'string')
@@ -701,15 +702,15 @@ function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
701702
const message = `<${emptyItems} empty item${ending}>`;
702703
output.push(ctx.stylize(message, 'undefined'));
703704
index = i;
704-
if (++visibleLength === ctx.maxArrayLength)
705+
if (++visibleLength === maxLength)
705706
break;
706707
}
707708
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
708709
elem, true));
709710
visibleLength++;
710711
index++;
711712
}
712-
if (index < value.length && visibleLength !== ctx.maxArrayLength) {
713+
if (index < value.length && visibleLength !== maxLength) {
713714
const len = value.length - index;
714715
const ending = len > 1 ? 's' : '';
715716
const message = `<${len} empty item${ending}>`;

test/parallel/test-util-inspect.js

+4
Original file line numberDiff line numberDiff line change
@@ -970,6 +970,10 @@ if (typeof Symbol !== 'undefined') {
970970
{
971971
const x = new Array(101).fill();
972972
assert(!util.inspect(x, { maxArrayLength: 101 }).endsWith('1 more item ]'));
973+
assert.strictEqual(
974+
util.inspect(x, { maxArrayLength: -1 }),
975+
'[ ... 101 more items ]'
976+
);
973977
}
974978

975979
{

0 commit comments

Comments
 (0)