Skip to content

Instantly share code, notes, and snippets.

@artalar
Created January 31, 2019 03:07
Show Gist options
  • Select an option

  • Save artalar/83f8945dd607a66629c448f74dd0777d to your computer and use it in GitHub Desktop.

Select an option

Save artalar/83f8945dd607a66629c448f74dd0777d to your computer and use it in GitHub Desktop.
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