Skip to content

Instantly share code, notes, and snippets.

@camilomontoyau
Forked from getify/test.js
Created September 11, 2020 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save camilomontoyau/c6b87c3a424db117019fe9580801a19c to your computer and use it in GitHub Desktop.
Save camilomontoyau/c6b87c3a424db117019fe9580801a19c to your computer and use it in GitHub Desktop.
fun call-stack experiment
function foo() {
baz();
}
function bar() {
baz();
}
function baz() {
console.log(`baz() was called from: ${whereWasICalledFrom()}`);
}
function whereWasICalledFrom() {
try {
throw new Error("");
}
catch (err) {
let stack = err.stack.toString();
let lines = stack.match(/^(.+)$/gm);
let callStackIdx = 0;
for (let line of lines) {
if (/^\s*at /.test(line)) {
if (callStackIdx < 2) {
callStackIdx++;
}
else {
let [,functionName] = line.match(/^\s*at ([^\s]+)/);
return functionName;
}
}
}
}
return "(unknown)";
}
baz();
// baz() was called from: test.js:36:1
foo();
// baz() was called from: foo
bar();
// baz() was called from: bar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment