-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
42 lines (42 loc) · 1.43 KB
/
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
interface UnlockFn { (): void; }
interface LockLinkedFn {
(): void;
next?: LockLinkedFn;
}
export class ReentrantLock {
private current?: LockLinkedFn;
private last?: LockLinkedFn;
private readonly chainNoop: LockLinkedFn = () => void (0);
private readonly chainNext: UnlockFn = () => {
if (this.current === this.last) {
this.current = this.last = undefined;
} else {
((this.current as LockLinkedFn).next as LockLinkedFn)();
}
}
public acquire(): Promise<UnlockFn> {
if (!this.last) {
let noop: LockLinkedFn | undefined = this.current = this.last = this.chainNoop;
return Promise.resolve(() => {
if (noop) {
noop = undefined;
this.chainNext();
}
});
} else {
return new Promise((resolve: (unlockFn: UnlockFn) => void) => {
let lockChainFn: LockLinkedFn | undefined = () => {
if (lockChainFn) {
this.current = lockChainFn;
lockChainFn = undefined;
resolve(this.chainNext);
}
};
this.last = (this.last as LockLinkedFn).next = lockChainFn;
});
}
}
public lock<T>(op: () => Promise<T>) {
return this.acquire().then(unlock => op().finally(unlock));
}
}