Skip to content
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
6 changes: 6 additions & 0 deletions lib/internal/util/inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ const {
SymbolIterator,
SymbolPrototypeToString,
SymbolPrototypeValueOf,
SymbolToPrimitive,
SymbolToStringTag,
TypedArrayPrototypeGetLength,
TypedArrayPrototypeGetSymbolToStringTag,
Expand Down Expand Up @@ -2103,6 +2104,11 @@ function hasBuiltInToString(value) {
value = proxyTarget;
}

// Check if value has a custom Symbol.toPrimitive transformation.
if (typeof value[SymbolToPrimitive] === 'function') {
return false;
}

// Count objects that have no `toString` function as built-in.
if (typeof value.toString !== 'function') {
return true;
Expand Down
21 changes: 21 additions & 0 deletions test/parallel/test-util-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,27 @@ assert.strictEqual(util.format('%s', -Infinity), '-Infinity');
);
}

// Symbol.toPrimitive handling for string format specifier
{
const objectWithToPrimitive = {
[Symbol.toPrimitive](hint) {
switch (hint) {
case 'number':
return 42;
case 'string':
return 'string representation';
case 'default':
default:
return 'default context';
}
}
};

assert.strictEqual(util.format('%s', +objectWithToPrimitive), '42');
assert.strictEqual(util.format('%s', objectWithToPrimitive), 'string representation');
assert.strictEqual(util.format('%s', objectWithToPrimitive + ''), 'default context');
}

// JSON format specifier
assert.strictEqual(util.format('%j'), '%j');
assert.strictEqual(util.format('%j', 42), '42');
Expand Down