#Custom console.log formatting for a class/object
7 messages · Page 1 of 1 (latest)
see Deno.inspect https://deno.land/api@v1.35.1?s=Deno.inspect
you can specify some options for how you want the object to be displayed https://deno.land/api@v1.35.1?s=Deno.InspectOptions
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
The Deno standard library comes with a
snapshot module, which
enables developers to write tests which assert a value against a reference
snap
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);
stdout
[ 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"), { ... })
Ooh thank you