Skip to content

Instantly share code, notes, and snippets.

@nyteshade
Created April 4, 2018 20:00
Show Gist options
  • Save nyteshade/19edd5051ace35158da21d9bd470993b to your computer and use it in GitHub Desktop.
Save nyteshade/19edd5051ace35158da21d9bd470993b to your computer and use it in GitHub Desktop.
A small patch to Function.prototype that helps make functions and classes a bit more self-documenting
// Patch Function.prototype to provide the signature in the REPL
Object.defineProperty(
Function.prototype,
'signature',
{
get() {
let source = this.toString()
// For classes we need to extract the signature of the
// constructor function within; so use some regular
// expressions in order to make that happen
if (source.startsWith('class')) {
let parts = /constructor\((.*?)\)\s*\{/.exec(source)
return `class ${this.name}(${parts[1]})`
}
// Otherwise, grab everything up to the first opening
// curly bracket and call it a day.
return source.slice(0, this.toString().indexOf('{')).trim()
}
}
)
@nyteshade
Copy link
Author

Subsequent usage might look like this

Person.signature // returns 'class Person(name)'
Array.signature // returns 'function Array()'
String.signature // returns 'function String()'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment