Skip to content

Commit 14b2db0

Browse files
committed
util: improve inspect() compact number mode
This fixes a proportion calculation for lots of short array entries with at least one bigger one that alone makes up for more than one fifth of all other entries together. PR-URL: #26984 Reviewed-By: Michaël Zasso <[email protected]> Reviewed-By: Matteo Collina <[email protected]>
1 parent 75007d6 commit 14b2db0

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

lib/internal/util/inspect.js

+4-3
Original file line numberDiff line numberDiff line change
@@ -878,26 +878,27 @@ function groupArrayElements(ctx, output) {
878878
let totalLength = 0;
879879
let maxLength = 0;
880880
let i = 0;
881+
const separatorSpace = 2; // Add 1 for the space and 1 for the separator.
881882
const dataLen = new Array(output.length);
882883
// Calculate the total length of all output entries and the individual max
883884
// entries length of all output entries. We have to remove colors first,
884885
// otherwise the length would not be calculated properly.
885886
for (; i < output.length; i++) {
886887
const len = ctx.colors ? removeColors(output[i]).length : output[i].length;
887888
dataLen[i] = len;
888-
totalLength += len;
889+
totalLength += len + separatorSpace;
889890
if (maxLength < len)
890891
maxLength = len;
891892
}
892893
// Add two to `maxLength` as we add a single whitespace character plus a comma
893894
// in-between two entries.
894-
const actualMax = maxLength + 2;
895+
const actualMax = maxLength + separatorSpace;
895896
// Check if at least three entries fit next to each other and prevent grouping
896897
// of arrays that contains entries of very different length (i.e., if a single
897898
// entry is longer than 1/5 of all other entries combined). Otherwise the
898899
// space in-between small entries would be enormous.
899900
if (actualMax * 3 + ctx.indentationLvl < ctx.breakLength &&
900-
(totalLength / maxLength > 5 || maxLength <= 6)) {
901+
(totalLength / actualMax > 5 || maxLength <= 6)) {
901902

902903
const approxCharHeights = 2.5;
903904
const bias = 1;

test/parallel/test-util-inspect.js

+24
Original file line numberDiff line numberDiff line change
@@ -2121,6 +2121,30 @@ assert.strictEqual(
21212121

21222122
assert.strictEqual(out, expected);
21232123

2124+
obj = [
2125+
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2126+
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2127+
1, 1, 1, 1, 1, 1, 123456789
2128+
];
2129+
2130+
out = util.inspect(obj, { compact: 3 });
2131+
2132+
expected = [
2133+
'[',
2134+
' 1, 1, 1,',
2135+
' 1, 1, 1,',
2136+
' 1, 1, 1,',
2137+
' 1, 1, 1,',
2138+
' 1, 1, 1,',
2139+
' 1, 1, 1,',
2140+
' 1, 1, 1,',
2141+
' 1, 1, 1,',
2142+
' 1, 1, 123456789',
2143+
']'
2144+
].join('\n');
2145+
2146+
assert.strictEqual(out, expected);
2147+
21242148
// Verify that array grouping and line consolidation does not happen together.
21252149
obj = {
21262150
a: {

0 commit comments

Comments
 (0)