Skip to content

Instantly share code, notes, and snippets.

@webbower
Created March 14, 2023 23:46
Show Gist options
  • Save webbower/32be5218eff08faf412f78d75b05646e to your computer and use it in GitHub Desktop.
Save webbower/32be5218eff08faf412f78d75b05646e to your computer and use it in GitHub Desktop.
JS Prototype boilerplate
const nodeCustomInspect = Symbol.for('nodejs.util.inspect.custom');
const denoCustomInspect = Symbol.for("Deno.customInspect");
const Ctor = () => ({});
Object.assign(Ctor, {
prototype: {
constructor: Ctor,
toString() {
return '';
},
valueOf() {
return 0;
},
[Symbol.toPrimitive](hint) {
if (hint === 'string') {
return this.toString();
}
return this.valueOf();
},
toJSON() {
return this.valueOf();
},
get [Symbol.toStringTag]() {
return Ctor.name;
},
toLog() {
return `${this[Symbol.toStringTag]} { ${this.toString()} }`;
},
[nodeCustomInspect](depth, opts) {
// console.log('nodeCustomInspect', depth, opts);
return this.toLog();
},
[denoCustomInspect](inspect, opts) {
// console.log('denoCustomInspect', inspect, opts);
return this.toLog();
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment