Created
April 17, 2018 09:19
-
-
Save Rovanion/4c1b99f43dd6b3d1f5087f226beb7863 to your computer and use it in GitHub Desktop.
A semitransparent print or log function for TypeScript or JavaScript
This file contains hidden or 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
let fnNameMatcher = /([^(]+)@|at ([^(]+) \(/; | |
function fnName(str: string) { | |
let regexResult = fnNameMatcher.exec(str) as string[]; | |
if (regexResult) { | |
return regexResult[1] || regexResult[2]; | |
} else { return ''; } | |
} | |
export function log(...messages: any[]) { | |
let logLines = (new Error().stack as string).split('\n'); | |
let callerName = fnName(logLines[1]); | |
if (callerName !== null) { | |
if (callerName !== 'log') { | |
console.log(callerName, ...messages); | |
} else { | |
console.log(fnName(logLines[2]), ...messages); | |
} | |
} else { | |
console.log(...messages); | |
} | |
return messages[0]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment