Skip to content

Commit

Permalink
inspect: Limit maximum number of printed items to 10
Browse files Browse the repository at this point in the history
  • Loading branch information
IvanGoncharov committed Mar 15, 2019
1 parent b699cfc commit b3d9a5c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
12 changes: 12 additions & 0 deletions src/jsutils/__tests__/inspect-test.js
Expand Up @@ -54,6 +54,18 @@ describe('inspect', () => {
expect(inspect([null])).to.equal('[null]');
expect(inspect([1, NaN])).to.equal('[1, NaN]');
expect(inspect([['a', 'b'], 'c'])).to.equal('[["a", "b"], "c"]');

expect(inspect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])).to.equal(
'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]',
);

expect(inspect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])).to.equal(
'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... 1 more item]',
);

expect(inspect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])).to.equal(
'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... 2 more items]',
);
});

it('object', () => {
Expand Down
22 changes: 21 additions & 1 deletion src/jsutils/inspect.js
Expand Up @@ -9,6 +9,8 @@

import nodejsCustomInspectSymbol from './nodejsCustomInspectSymbol';

const MAX_ARRAY_LENGTH = 10;

/**
* Used to print values in error messages.
*/
Expand All @@ -29,7 +31,7 @@ export default function inspect(value: mixed): string {
? customValue
: inspect(customValue);
} else if (Array.isArray(value)) {
return '[' + value.map(inspect).join(', ') + ']';
return inspectArray(value);
}

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

function inspectArray(array) {
const len = Math.min(MAX_ARRAY_LENGTH, array.length);
const remaining = array.length - len;
const items = [];

for (let i = 0; i < len; ++i) {
items.push(inspect(array[i]));
}

if (remaining === 1) {
items.push('... 1 more item');
} else if (remaining > 1) {
items.push(`... ${remaining} more items`);
}

return '[' + items.join(', ') + ']';
}

function getCustomFn(object) {
const customInspectFn = object[String(nodejsCustomInspectSymbol)];

Expand Down

0 comments on commit b3d9a5c

Please sign in to comment.