Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: passing options to custom inspect #40

Merged
merged 1 commit into from
May 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,9 @@ function addNumericSeparator(num, str) {
return $replace.call(str, sepRegex, '$&_');
}

var inspectCustom = require('./util.inspect').custom;
var inspectSymbol = inspectCustom && isSymbol(inspectCustom) ? inspectCustom : null;
var utilInspect = require('./util.inspect');
var inspectCustom = utilInspect.custom;
var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null;

module.exports = function inspect_(obj, options, depth, seen) {
var opts = options || {};
Expand Down Expand Up @@ -193,8 +194,8 @@ module.exports = function inspect_(obj, options, depth, seen) {
return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }';
}
if (typeof obj === 'object' && customInspect) {
if (inspectSymbol && typeof obj[inspectSymbol] === 'function') {
return obj[inspectSymbol]();
if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) {
return utilInspect(obj, { depth: maxDepth - depth });
} else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') {
return obj.inspect();
}
Expand Down
37 changes: 37 additions & 0 deletions test/inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,40 @@ test('maxStringLength', function (t) {

t.end();
});

test('inspect options', { skip: !utilInspect.custom }, function (t) {
var obj = {};
obj[utilInspect.custom] = function () {
return JSON.stringify(arguments);
};
t.equal(
inspect(obj),
utilInspect(obj, { depth: 5 }),
'custom symbols will use node\'s inspect'
);
t.equal(
inspect(obj, { depth: 2 }),
utilInspect(obj, { depth: 2 }),
'a reduced depth will be passed to node\'s inspect'
);
t.equal(
inspect({ d1: obj }, { depth: 3 }),
'{ d1: ' + utilInspect(obj, { depth: 2 }) + ' }',
'deep objects will receive a reduced depth'
);
t.equal(
inspect({ d1: obj }, { depth: 1 }),
'{ d1: [Object] }',
'unlike nodejs inspect, customInspect will not be used once the depth is exceeded.'
);
t.end();
});

test('inspect URL', { skip: typeof URL === 'undefined' }, function (t) {
t.match(
inspect(new URL('https://nodejs.org')),
/nodejs\.org/, // Different environments stringify it differently
'url can be inspected'
);
t.end();
});