generated from legendecas/tc39-proposal
-
Notifications
You must be signed in to change notification settings - Fork 14
/
index.ts
45 lines (38 loc) · 927 Bytes
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
type AnyFunc = (...args: any) => any;
type Storage = Map<AsyncContext<unknown>, unknown>;
let __storage__: Storage = new Map();
export class AsyncContext<T> {
static wrap<F extends AnyFunc>(fn: F): F {
const current = __storage__;
function wrap(...args: Parameters<F>): ReturnType<F> {
return run(fn, current, this, args);
};
return wrap as unknown as F;
}
run<F extends AnyFunc>(
value: T,
fn: F,
...args: Parameters<F>
): ReturnType<F> {
const next = new Map(__storage__);
next.set(this, value);
return run(fn, next, null, args);
}
get(): T {
return __storage__.get(this) as T;
}
}
function run<F extends AnyFunc>(
fn: F,
next: Storage,
binding: ThisType<F>,
args: Parameters<F>
): ReturnType<F> {
const previous = __storage__;
try {
__storage__ = next;
return fn.apply(binding, args);
} finally {
__storage__ = previous;
}
}