Skip to content

Instantly share code, notes, and snippets.

@thatkookooguy
Last active January 27, 2020 14:20
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 thatkookooguy/d962fe11df937ddc7d26147095043953 to your computer and use it in GitHub Desktop.
Save thatkookooguy/d962fe11df937ddc7d26147095043953 to your computer and use it in GitHub Desktop.
get call location of function for tests\logs\etc.
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