Last active
January 27, 2020 14:20
-
-
Save thatkookooguy/d962fe11df937ddc7d26147095043953 to your computer and use it in GitHub Desktop.
get call location of function for tests\logs\etc.
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 getCallLocation(stopStackFnName) { | |
stopStackFnName = stopStackFnName || 'getCallLocation'; | |
function getErrorObject() { | |
try { | |
throw new Error(''); | |
} catch (err) { | |
return err; | |
} | |
} | |
const err = getErrorObject(); | |
const stack = err.stack.split(/\r?\n/).map((line) => line.trim()); | |
const thisFunctionCall = stack.find((stackLine) => stackLine.startsWith(`at ${ stopStackFnName }`)); | |
const indexOfThisFunction = stack.indexOf(thisFunctionCall); | |
const lineOfCall = stack[indexOfThisFunction + 1]; | |
const insideBrackets = lineOfCall.replace(/^.*\(/, '').replace(/\).*$/, ''); | |
const getLineAndColumnNumbersRegex = /:(\d+):(\d+)$/; | |
const result = getLineAndColumnNumbersRegex.exec(insideBrackets); | |
return { | |
line: result[1], | |
column: result[2] | |
}; | |
} | |
const location = getCallLocation(); | |
console.log(location); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment