Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b3d9a5c

Browse files
committed
inspect: Limit maximum number of printed items to 10
1 parent b699cfc commit b3d9a5c

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

src/jsutils/__tests__/inspect-test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,18 @@ describe('inspect', () => {
5454
expect(inspect([null])).to.equal('[null]');
5555
expect(inspect([1, NaN])).to.equal('[1, NaN]');
5656
expect(inspect([['a', 'b'], 'c'])).to.equal('[["a", "b"], "c"]');
57+
58+
expect(inspect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])).to.equal(
59+
'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]',
60+
);
61+
62+
expect(inspect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])).to.equal(
63+
'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... 1 more item]',
64+
);
65+
66+
expect(inspect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])).to.equal(
67+
'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... 2 more items]',
68+
);
5769
});
5870

5971
it('object', () => {

src/jsutils/inspect.js

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99

1010
import nodejsCustomInspectSymbol from './nodejsCustomInspectSymbol';
1111

12+
const MAX_ARRAY_LENGTH = 10;
13+
1214
/**
1315
* Used to print values in error messages.
1416
*/
@@ -29,7 +31,7 @@ export default function inspect(value: mixed): string {
2931
? customValue
3032
: inspect(customValue);
3133
} else if (Array.isArray(value)) {
32-
return '[' + value.map(inspect).join(', ') + ']';
34+
return inspectArray(value);
3335
}
3436

3537
const properties = Object.keys(value)
@@ -43,6 +45,24 @@ export default function inspect(value: mixed): string {
4345
}
4446
}
4547

48+
function inspectArray(array) {
49+
const len = Math.min(MAX_ARRAY_LENGTH, array.length);
50+
const remaining = array.length - len;
51+
const items = [];
52+
53+
for (let i = 0; i < len; ++i) {
54+
items.push(inspect(array[i]));
55+
}
56+
57+
if (remaining === 1) {
58+
items.push('... 1 more item');
59+
} else if (remaining > 1) {
60+
items.push(`... ${remaining} more items`);
61+
}
62+
63+
return '[' + items.join(', ') + ']';
64+
}
65+
4666
function getCustomFn(object) {
4767
const customInspectFn = object[String(nodejsCustomInspectSymbol)];
4868

0 commit comments

Comments
 (0)