Created
June 14, 2024 10:20
-
-
Save SparK-Cruz/94faad2c13ee3bceef048d56e51f4570 to your computer and use it in GitHub Desktop.
Get the caller context for any function after arguments.callee.caller deprecation
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
/** | |
* Usage: | |
* import callerProp from "./caller.js"; | |
* Object.defineProperty(global, "__caller", callerProp); | |
* | |
* function A() { | |
* return B(); | |
* } | |
* function B() { | |
* console.log(__caller.name); // A | |
* console.log(typeof __caller); // Function | |
* } | |
*/ | |
export default { | |
configurable: true, | |
enumerable: false, | |
get: function() { | |
const _prepareStackTrace = Error.prepareStackTrace; | |
try { | |
let result = null; | |
Error.prepareStackTrace = (_, callSites) => { | |
// Ignores this property (0) and the callee (1) | |
result = callSites[2] ?? null; | |
return callSites; | |
}; | |
new Error().stack; // eslint-disable-line unicorn/error-message, no-unused-expressions | |
if (!result) { | |
return null; | |
} | |
return result.getFunction(); | |
} finally { | |
Error.prepareStackTrace = _prepareStackTrace; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment