Skip to content

Instantly share code, notes, and snippets.

@getify
Created August 27, 2020 20:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save getify/6cd5fdd0b9c33310e8f57cb917d37f7d to your computer and use it in GitHub Desktop.
Save getify/6cd5fdd0b9c33310e8f57cb917d37f7d 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