Skip to content

Instantly share code, notes, and snippets.

@sidoshi
Created July 30, 2020 14:22
Show Gist options
  • Save sidoshi/d24e30e18b3c9bc1c62f33dd8b066182 to your computer and use it in GitHub Desktop.
Save sidoshi/d24e30e18b3c9bc1c62f33dd8b066182 to your computer and use it in GitHub Desktop.
A React context-like implementation for functions
const contextStore: any = {};
const prefix = '____FREIGHTHUB_CONTEXT_PROVIDER____';
export async function runInContext(
callback: () => Promise<void>,
context: any
) {
const id = 'some-random-id';
const rootFnName = `${prefix}${id}--end`;
contextStore[id] = context;
const caller = {
[rootFnName]: callback,
};
await caller[rootFnName]();
delete contextStore[id];
}
export function getContext() {
const defaultStackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = Infinity;
const trace = new Error().stack;
const contextId = (trace?.match(
/____FREIGHTHUB_CONTEXT_PROVIDER____(.*?)--end/
) as RegExpMatchArray)[1];
Error.stackTraceLimit = defaultStackTraceLimit;
return contextStore[contextId];
}
const a = () => console.log(getContext());
const b = () => a();
const c = () => b();
const d = () => c();
runInContext(async () => d(), 'context value for this call stack');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment