@@ -35,12 +35,15 @@ const DEBUG = window?.location?.search?.includes("_debug_spreadsheet");
35
35
class CellIdMap {
36
36
ids : string [ ] = [ ] ;
37
37
static MAX_COLS = 1000000000 ;
38
+ static getCellIndex ( row : number , col : number ) : number {
39
+ return row * CellIdMap . MAX_COLS + col ;
40
+ }
38
41
insert ( row : number , col : number , id : string ) {
39
- const idx = row * CellIdMap . MAX_COLS + col ;
42
+ const idx = CellIdMap . getCellIndex ( row , col ) ;
40
43
this . ids [ idx ] = id ;
41
44
}
42
45
get ( row : number , col : number ) : string | undefined {
43
- const idx = row * CellIdMap . MAX_COLS + col ;
46
+ const idx = CellIdMap . getCellIndex ( row , col ) ;
44
47
return this . ids [ idx ] ;
45
48
}
46
49
}
@@ -181,11 +184,8 @@ const performUpdate = async (params: UpdateParams) => {
181
184
} ;
182
185
183
186
async function processGroupedUpdates ( updates : UpdateParams [ ] ) {
184
- const grouped = new Map (
185
- updates . map ( ( update ) => [ `${ update . x } -${ update . y } ` , update ] ) ,
186
- ) ;
187
- const uniques = Array . from ( grouped . values ( ) ) ;
188
- await Promise . all ( uniques . map ( performUpdate ) ) ;
187
+ deduplicate ( updates , ( { x, y } ) => CellIdMap . getCellIndex ( y , x ) ) ;
188
+ await Promise . all ( updates . map ( performUpdate ) ) ;
189
189
}
190
190
191
191
const handleUpdate = debounce ( processGroupedUpdates , 50 ) ;
@@ -353,3 +353,19 @@ const elem = elems[elems.length - 1];
353
353
if ( ! ( elem instanceof HTMLElement ) )
354
354
throw new Error ( "No spreadsheet elements found" ) ;
355
355
renderSpreadsheetToElement ( elem ) ;
356
+
357
+ /** Keeps only the last occurrence of each item in the array */
358
+ function deduplicate < T , Y > ( arr : T [ ] , getKey : ( item : T ) => Y ) : void {
359
+ const keyPositions = new Map < Y , number > ( ) ;
360
+ let writeAt = 0 ;
361
+
362
+ for ( let readAt = 0 ; readAt < arr . length ; readAt ++ ) {
363
+ const item = arr [ readAt ] ;
364
+ const key = getKey ( item ) ;
365
+ const writePos = keyPositions . get ( key ) ?? writeAt ++ ;
366
+ keyPositions . set ( key , readAt ) ;
367
+ arr [ writePos ] = item ;
368
+ }
369
+
370
+ arr . length = writeAt ;
371
+ }
0 commit comments