Skip to content

Instantly share code, notes, and snippets.

@SparK-Cruz
Created June 14, 2024 10:20
Show Gist options
  • Save SparK-Cruz/94faad2c13ee3bceef048d56e51f4570 to your computer and use it in GitHub Desktop.
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
/**
* 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