Created
April 4, 2018 20:00
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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() | |
| } | |
| } | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Subsequent usage might look like this