File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 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+ } ;
You can’t perform that action at this time.
0 commit comments