Skip to content

Commit 2f3337c

Browse files
committed
fix: Use Map for O(1) column lookups in table width calculations
1 parent 1a5715e commit 2f3337c

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

src/table/use-column-widths.tsx

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
22
// SPDX-License-Identifier: Apache-2.0
3-
import React, { createContext, useContext, useEffect, useRef, useState } from 'react';
3+
import React, { createContext, useContext, useEffect, useMemo, useRef, useState } from 'react';
44

55
import { useResizeObserver, useStableCallback } from '@cloudscape-design/component-toolkit/internal';
66
import { getLogicalBoundingClientRect } from '@cloudscape-design/component-toolkit/internal';
@@ -35,12 +35,12 @@ function readWidths(
3535
}
3636

3737
function updateWidths(
38-
visibleColumns: readonly ColumnWidthDefinition[],
38+
columnById: Map<PropertyKey, ColumnWidthDefinition>,
3939
oldWidths: Map<PropertyKey, number>,
4040
newWidth: number,
4141
columnId: PropertyKey
4242
) {
43-
const column = visibleColumns.find(column => column.id === columnId);
43+
const column = columnById.get(columnId);
4444
let minWidth = DEFAULT_COLUMN_WIDTH;
4545
if (typeof column?.width === 'number' && column.width < DEFAULT_COLUMN_WIDTH) {
4646
minWidth = column?.width;
@@ -83,6 +83,9 @@ export function ColumnWidthsProvider({ visibleColumns, resizableColumns, contain
8383
const containerWidthRef = useRef(0);
8484
const [columnWidths, setColumnWidths] = useState<null | Map<PropertyKey, number>>(null);
8585

86+
// Pre-build a Map for column lookups
87+
const columnById = useMemo(() => new Map(visibleColumns.map(column => [column.id, column])), [visibleColumns]);
88+
8689
const cellsRef = useRef(new Map<PropertyKey, HTMLElement>());
8790
const stickyCellsRef = useRef(new Map<PropertyKey, HTMLElement>());
8891
const getCell = (columnId: PropertyKey): null | HTMLElement => cellsRef.current.get(columnId) ?? null;
@@ -96,7 +99,7 @@ export function ColumnWidthsProvider({ visibleColumns, resizableColumns, contain
9699
};
97100

98101
const getColumnStyles = (sticky: boolean, columnId: PropertyKey): ColumnWidthStyle => {
99-
const column = visibleColumns.find(column => column.id === columnId);
102+
const column = columnById.get(columnId);
100103
if (!column) {
101104
return {};
102105
}
@@ -190,7 +193,7 @@ export function ColumnWidthsProvider({ visibleColumns, resizableColumns, contain
190193
}, []);
191194

192195
function updateColumn(columnId: PropertyKey, newWidth: number) {
193-
setColumnWidths(columnWidths => updateWidths(visibleColumns, columnWidths ?? new Map(), newWidth, columnId));
196+
setColumnWidths(columnWidths => updateWidths(columnById, columnWidths ?? new Map(), newWidth, columnId));
194197
}
195198

196199
return (

0 commit comments

Comments
 (0)