Skip to content

Commit 24a57df

Browse files
authored
Create query-batching.ts
1 parent 6bbc2fb commit 24a57df

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

TypeScript/query-batching.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Time: O(1)
2+
// Space: O(1)
3+
4+
class QueryBatcher {
5+
#queryMultiple : (keys: string[]) => Promise<string[]>
6+
#t : number
7+
#last : number
8+
#pending : any[]
9+
10+
constructor(queryMultiple: (keys: string[]) => Promise<string[]>, t: number) {
11+
this.#queryMultiple = queryMultiple;
12+
this.#t = t;
13+
this.#last = 0;
14+
this.#pending = [];
15+
}
16+
17+
async getValue(key: string): Promise<string> {
18+
return new Promise((resolve) => {
19+
const curr = Date.now();
20+
const remain = Math.max((this.#t + this.#last) - curr, 0);
21+
this.#last = curr + remain;
22+
this.#pending.push({key, resolve});
23+
if (this.#pending.length === 1) {
24+
setTimeout(() => this.processPending(), remain);
25+
}
26+
});
27+
}
28+
29+
async processPending() {
30+
this.#last = Date.now();
31+
const pending = this.#pending;
32+
this.#pending = [];
33+
34+
const result = await this.#queryMultiple(pending.map((obj) => obj.key));
35+
pending.map((obj, i) => obj.resolve(result[i]));
36+
}
37+
};

0 commit comments

Comments
 (0)