-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
query-batching.ts
37 lines (32 loc) · 1.06 KB
/
query-batching.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
// Time: O(n)
// Space: O(n)
class QueryBatcher {
#queryMultiple : (keys: string[]) => Promise<string[]>
#t : number
#last : number
#pending : any[]
constructor(queryMultiple: (keys: string[]) => Promise<string[]>, t: number) {
this.#queryMultiple = queryMultiple;
this.#t = t;
this.#last = 0;
this.#pending = [];
}
async getValue(key: string): Promise<string> {
return new Promise((resolve) => {
const curr = Date.now();
const remain = Math.max((this.#t + this.#last) - curr, 0);
this.#last = curr + remain;
this.#pending.push({key, resolve});
if (this.#pending.length === 1) {
setTimeout(() => this.#processPending(), remain);
}
});
}
async #processPending() {
this.#last = Date.now();
const pending = this.#pending;
this.#pending = [];
const result = await this.#queryMultiple(pending.map((obj) => obj.key));
pending.map((obj, i) => obj.resolve(result[i]));
}
};