-
-
Notifications
You must be signed in to change notification settings - Fork 34.2k
Description
Currently when using [Symbol.for('nodejs.util.inspect.custom')](depth, opts) in cross-environment code we have a problem when wanting to use the results of util.inspect on inner values of our value.
For example consider an implementation of Complex like so:
class Complex {
#real;
#imag;
constructor(real, imag) {
this.#real = real;
this.#imag = imag;
}
get real() {
return this.#real;
}
get imag() {
return this.#imag;
}
}If we wish to extend it with [Symbol.for('nodejs.util.custom.inspect')] we can do something like the following:
class Complex {
// ...
[Symbol.for('nodejs.util.inspect.custom')]() {
return `Complex { real: ${ this.#real }, imag: ${ this.#imag } }`
}
}However this has the downside of losing the color-formatting on the numbers. In order to fix this we could import util.inspect and use it as follows:
import { inspect } from 'util';
class Complex {
// ...
[Symbol.for('nodejs.util.inspect.custom')]() {
return `Complex { real: ${ inspect(this.#real) }, imag: ${ inspect(this.#imag) } }`
}
}However now we have made our code non-portable by importing util, even though this code has no other dependencies on Node.
As such I'd like to propose passing inspect into [Symbol.for('nodejs.util.inspect.custom')]() as the third argument so that we could write it like so:
class Complex {
// ...
[Symbol.for('nodejs.util.inspect.custom')](depth, opts, inspect) {
return `Complex { real: ${ inspect(this.#real) }, imag: ${ inspect(this.#imag) } }`;
}