|
| 1 | +import { getMemoOptions, memo, RowData, Table } from "@tanstack/react-table"; |
| 2 | + |
| 3 | +/** |
| 4 | + * Returns an array of two numbers, the minimum and maximum values for the column, or undefined if the column does not exist or has no values. |
| 5 | + * Customized version of the default getFacetedMinMaxValues function from tanstack table handling mixed null and possible NaN values. |
| 6 | + * See https://tanstack.com/table/v8/docs/api/features/column-faceting#getfacetedminmaxvalues. |
| 7 | + * @returns An array of two numbers, the minimum and maximum values for the column, or undefined if the column does not exist or has no values. |
| 8 | + */ |
| 9 | +export function getFacetedMinMaxValues<TData extends RowData>(): ( |
| 10 | + table: Table<TData>, |
| 11 | + columnId: string |
| 12 | +) => () => undefined | [number, number] { |
| 13 | + // eslint-disable-next-line sonarjs/cognitive-complexity -- Customized copy of tanstack table function. |
| 14 | + return (table, columnId) => |
| 15 | + memo( |
| 16 | + () => [table.getColumn(columnId)?.getFacetedRowModel()], |
| 17 | + (facetedRowModel) => { |
| 18 | + if (!facetedRowModel) return undefined; |
| 19 | + |
| 20 | + // Initialize with the smallest and largest possible numbers. |
| 21 | + const facetedMinMaxValues: [number, number] = [Infinity, -Infinity]; |
| 22 | + |
| 23 | + for (let i = 0; i < facetedRowModel.flatRows.length; i++) { |
| 24 | + const values = |
| 25 | + facetedRowModel.flatRows[i]!.getUniqueValues<number>(columnId); |
| 26 | + |
| 27 | + for (let j = 0; j < values.length; j++) { |
| 28 | + const value = values[j]!; |
| 29 | + // Convert value to a number. |
| 30 | + const numericValue = Number(value); |
| 31 | + |
| 32 | + // Skip null and NaN values. |
| 33 | + if (value === null || isNaN(numericValue)) continue; |
| 34 | + |
| 35 | + if (numericValue < facetedMinMaxValues[0]) { |
| 36 | + facetedMinMaxValues[0] = numericValue; |
| 37 | + } else if (numericValue > facetedMinMaxValues[1]) { |
| 38 | + facetedMinMaxValues[1] = numericValue; |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return facetedMinMaxValues; |
| 44 | + }, |
| 45 | + getMemoOptions(table.options, "debugTable", "getFacetedMinMaxValues") |
| 46 | + ); |
| 47 | +} |
0 commit comments