Created
August 27, 2020 20:32
-
-
Save getify/6cd5fdd0b9c33310e8f57cb917d37f7d 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