Skip to content

Commit 86dc8f7

Browse files
committed
perf
1 parent bce284e commit 86dc8f7

File tree

1 file changed

+23
-7
lines changed

1 file changed

+23
-7
lines changed

src/spreadsheet.ts

+23-7
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,15 @@ const DEBUG = window?.location?.search?.includes("_debug_spreadsheet");
3535
class CellIdMap {
3636
ids: string[] = [];
3737
static MAX_COLS = 1000000000;
38+
static getCellIndex(row: number, col: number): number {
39+
return row * CellIdMap.MAX_COLS + col;
40+
}
3841
insert(row: number, col: number, id: string) {
39-
const idx = row * CellIdMap.MAX_COLS + col;
42+
const idx = CellIdMap.getCellIndex(row, col);
4043
this.ids[idx] = id;
4144
}
4245
get(row: number, col: number): string | undefined {
43-
const idx = row * CellIdMap.MAX_COLS + col;
46+
const idx = CellIdMap.getCellIndex(row, col);
4447
return this.ids[idx];
4548
}
4649
}
@@ -181,11 +184,8 @@ const performUpdate = async (params: UpdateParams) => {
181184
};
182185

183186
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));
189189
}
190190

191191
const handleUpdate = debounce(processGroupedUpdates, 50);
@@ -353,3 +353,19 @@ const elem = elems[elems.length - 1];
353353
if (!(elem instanceof HTMLElement))
354354
throw new Error("No spreadsheet elements found");
355355
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

Comments
 (0)