-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
util.ts
48 lines (44 loc) 路 1.04 KB
/
util.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
46
47
48
// Copyright 2019 Yusuke Sakurai. All rights reserved. MIT license.
import {
deferred,
Deferred,
} from "./vendor/https/deno.land/std/util/async.ts";
export function pathResolver(meta: ImportMeta): (p: string) => string {
return (p) => new URL(p, meta.url).pathname;
}
export async function readString(r: Deno.Reader): Promise<string> {
const buf = new Deno.Buffer();
await Deno.copy(buf, r);
return buf.toString();
}
export interface PromiseWaitQueue<T, P> {
enqueue(t: T): Promise<P>;
}
export function promiseWaitQueue<T, P>(
creator: (t: T) => Promise<P>,
): PromiseWaitQueue<T, P> {
const queue: {
d: Deferred<P>;
t: T;
}[] = [];
function enqueue(t: T): Promise<P> {
const d = deferred<P>();
queue.push({ d, t });
if (queue.length === 1) {
dequeue();
}
return d;
}
function dequeue() {
const [e] = queue;
if (!e) return;
creator(e.t)
.then(e.d.resolve)
.catch(e.d.reject)
.finally(() => {
queue.shift();
dequeue();
});
}
return { enqueue };
}