Skip to content

Commit d60840a

Browse files
committed
feat: optimize lookup speed by doing it once
1 parent 267898c commit d60840a

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

packages/core/src/utils/randomSafeContext.ts

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,28 @@ import { GLOBAL_OBJ } from './worldwide';
22

33
export type RandomSafeContextRunner = <T>(callback: () => T) => T;
44

5-
let RESOLVED_RUNNER: RandomSafeContextRunner | undefined;
5+
// undefined = not yet resolved, null = no runner found, function = runner found
6+
let RESOLVED_RUNNER: RandomSafeContextRunner | null | undefined;
67

78
/**
89
* Simple wrapper that allows SDKs to *secretly* set context wrapper to generate safe random IDs in cache components contexts
910
*/
1011
export function withRandomSafeContext<T>(cb: () => T): T {
11-
// Skips future symbol lookups if we've already resolved the runner once
12-
if (RESOLVED_RUNNER) {
13-
return RESOLVED_RUNNER(cb);
12+
// Skips future symbol lookups if we've already resolved (or attempted to resolve) the runner once
13+
if (RESOLVED_RUNNER !== undefined) {
14+
return RESOLVED_RUNNER ? RESOLVED_RUNNER(cb) : cb();
1415
}
1516

1617
const sym = Symbol.for('__SENTRY_SAFE_RANDOM_ID_WRAPPER__');
1718
const globalWithSymbol: typeof GLOBAL_OBJ & { [sym]?: RandomSafeContextRunner } = GLOBAL_OBJ;
18-
if (!(sym in globalWithSymbol) || typeof globalWithSymbol[sym] !== 'function') {
19-
return cb();
20-
}
2119

22-
RESOLVED_RUNNER = globalWithSymbol[sym];
20+
if (sym in globalWithSymbol && typeof globalWithSymbol[sym] === 'function') {
21+
RESOLVED_RUNNER = globalWithSymbol[sym];
22+
return RESOLVED_RUNNER(cb);
23+
}
2324

24-
return globalWithSymbol[sym](cb);
25+
RESOLVED_RUNNER = null;
26+
return cb();
2527
}
2628

2729
/**

0 commit comments

Comments
 (0)