-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.tsx
63 lines (50 loc) · 1.37 KB
/
utils.tsx
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
export async function wait(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export async function nextTick() {
return new Promise((resolve) => requestAnimationFrame(resolve));
}
export function getLinkInAnscenstor(e: EventTarget | null): string | null {
if (e instanceof HTMLAnchorElement) return e.href;
else if (e instanceof SVGAElement) return e.href.animVal;
if (e instanceof Element) return getLinkInAnscenstor(e.parentElement);
return null;
}
export function randomWithin(a: number, b: number): number {
return a + Math.random() * (b - a);
}
export class SemiReactive<T> {
data: T | null;
promise: Promise<void>;
resolve: () => void;
constructor() {
this.data = null;
let r: () => void;
this.promise = new Promise((resolve) => (r = resolve));
this.resolve = r!;
}
set(value: T) {
const orig = this.data;
this.data = value;
if (orig === null) this.resolve();
}
async get(): Promise<T> {
if (this.data === null) await this.promise;
return this.data!;
}
}
const Blackhole = new Promise(() => {});
export class Debouncer {
epoch: number;
delay: number;
constructor(delay: number) {
this.epoch = 0;
this.delay = delay;
}
async notify(): Promise<void> {
this.epoch++;
const cur = this.epoch;
await wait(this.delay);
if (cur !== this.epoch) await Blackhole;
}
}