diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index b2ac7200c48772..9280e2ac5faab1 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -878,6 +878,7 @@ function groupArrayElements(ctx, output) { let totalLength = 0; let maxLength = 0; let i = 0; + const separatorSpace = 2; // Add 1 for the space and 1 for the separator. const dataLen = new Array(output.length); // Calculate the total length of all output entries and the individual max // entries length of all output entries. We have to remove colors first, @@ -885,19 +886,19 @@ function groupArrayElements(ctx, output) { for (; i < output.length; i++) { const len = ctx.colors ? removeColors(output[i]).length : output[i].length; dataLen[i] = len; - totalLength += len; + totalLength += len + separatorSpace; if (maxLength < len) maxLength = len; } // Add two to `maxLength` as we add a single whitespace character plus a comma // in-between two entries. - const actualMax = maxLength + 2; + const actualMax = maxLength + separatorSpace; // Check if at least three entries fit next to each other and prevent grouping // of arrays that contains entries of very different length (i.e., if a single // entry is longer than 1/5 of all other entries combined). Otherwise the // space in-between small entries would be enormous. if (actualMax * 3 + ctx.indentationLvl < ctx.breakLength && - (totalLength / maxLength > 5 || maxLength <= 6)) { + (totalLength / actualMax > 5 || maxLength <= 6)) { const approxCharHeights = 2.5; const bias = 1; diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index 547399f763d24d..300ab5524a5c3a 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -2121,6 +2121,30 @@ assert.strictEqual( assert.strictEqual(out, expected); + obj = [ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 123456789 + ]; + + out = util.inspect(obj, { compact: 3 }); + + expected = [ + '[', + ' 1, 1, 1,', + ' 1, 1, 1,', + ' 1, 1, 1,', + ' 1, 1, 1,', + ' 1, 1, 1,', + ' 1, 1, 1,', + ' 1, 1, 1,', + ' 1, 1, 1,', + ' 1, 1, 123456789', + ']' + ].join('\n'); + + assert.strictEqual(out, expected); + // Verify that array grouping and line consolidation does not happen together. obj = { a: {