NeTT
NeTT16mo ago

Custom console.log formatting for a class/object

Is there a way to change the way an object/class is printed in the console? For example, instead of
[1, 2, 3, 4]
[1, 2, 3, 4]
, I want the particular object to be printed as
[1, 2
3, 4]
[1, 2
3, 4]
5 Replies
ybabts
ybabts16mo ago
you can specify some options for how you want the object to be displayed https://deno.land/api@v1.35.1?s=Deno.InspectOptions
Deno
Deno.InspectOptions | Runtime APIs | Deno
Option which can be specified when performing {@linkcode Deno.inspect}.
ybabts
ybabts16mo ago
if you want to have a more specific way of displaying your object, you can use the Deno.customInspect symbol to implement your own way of inspecting the object https://deno.land/manual@v1.35.1/basics/testing/snapshot_testing#serialization-with--denocustominspect
Deno
Snapshots | Manual | Deno
The Deno standard library comes with a snapshot module, which enables developers to write tests which assert a value against a reference snap
ybabts
ybabts16mo ago
Here's a little example it showing off
const myarray = [1, 2, 3, 4, 5, 6];

console.log(myarray);
console.log(Deno.inspect(myarray, {
breakLength: 28,
}));
Object.defineProperty(myarray, Symbol.for("Deno.customInspect"), {
value() {
const splits = String(this).split(",");
let str = "";
for (let i = 0; i < splits.length; i += 2) {
str += (i !== 0 ? " " : "") + (splits[i] + ", " + splits[i + 1] ?? "") +
(i > splits.length / 2 ? "" : "\n");
}
return `[${str}]`;
},
});
console.log(myarray);
const myarray = [1, 2, 3, 4, 5, 6];

console.log(myarray);
console.log(Deno.inspect(myarray, {
breakLength: 28,
}));
Object.defineProperty(myarray, Symbol.for("Deno.customInspect"), {
value() {
const splits = String(this).split(",");
let str = "";
for (let i = 0; i < splits.length; i += 2) {
str += (i !== 0 ? " " : "") + (splits[i] + ", " + splits[i + 1] ?? "") +
(i > splits.length / 2 ? "" : "\n");
}
return `[${str}]`;
},
});
console.log(myarray);
stdout
[ 1, 2, 3, 4, 5, 6 ]
[
1,
2,
3,
4,
5,
6
]
[1, 2
3, 4
5, 6]
[ 1, 2, 3, 4, 5, 6 ]
[
1,
2,
3,
4,
5,
6
]
[1, 2
3, 4
5, 6]
you can also define it for specific object classes as well if you want, or implement the symbol in your own class
Object.defineProperty(Array.prototype, Symbol.for("Deno.customInspect"), { ... })
Object.defineProperty(Array.prototype, Symbol.for("Deno.customInspect"), { ... })
NeTT
NeTT16mo ago
Ooh thank you I'll take a look into it