-
-
Save camilomontoyau/c6b87c3a424db117019fe9580801a19c to your computer and use it in GitHub Desktop.
fun call-stack experiment
This file contains 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 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