Created
January 31, 2019 03:07
-
-
Save artalar/83f8945dd607a66629c448f74dd0777d to your computer and use it in GitHub Desktop.
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
| function getCaller() { | |
| const stack = getStack(); | |
| stack.shift(); // getStack | |
| stack.shift(); // getCaller | |
| // Return caller's caller | |
| return stack; | |
| } | |
| function getStack() { | |
| // Save original Error.prepareStackTrace | |
| const origPrepareStackTrace = Error.prepareStackTrace; | |
| // Override with function that just returns `stack` | |
| Error.prepareStackTrace = (_, stack) => stack; | |
| // Create a new `Error`, which automatically gets `stack` | |
| // Evaluate `err.stack`, which calls our new `Error.prepareStackTrace` | |
| const { stack } = new Error(); | |
| // Restore original `Error.prepareStackTrace` | |
| Error.prepareStackTrace = origPrepareStackTrace; | |
| // Remove superfluous function call on stack | |
| stack.shift(); // getStack --> Error | |
| return stack; | |
| } | |
| // EXAMPLE | |
| // (() => getCaller())()[0].toString() | |
| // "<anonymous>:1:20" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment