UNPKG

@carbon/react

Version:

React components for the Carbon Design System

92 lines (83 loc) 2.51 kB
/** * Copyright IBM Corp. 2016, 2023 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var cells = require('./cells.js'); var sortStates = require('../state/sortStates.js'); /** * Compare two values to determine their order. If both values have the same * type, the default sort algorithm will be used for those types. Otherwise, the * values will be converted to strings for comparison. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- https://github.com/carbon-design-system/carbon/issues/20452 const compare = (a, b, locale = 'en') => { // prevent multiple null values in one column (sorting breaks) if (a === null) a = ''; if (b === null) b = ''; if (typeof a === 'number' && typeof b === 'number') { return a - b; } if (typeof a === 'string' && typeof b === 'string') { return compareStrings(a, b, locale); } const aChild = a?.props?.children; const bChild = b?.props?.children; if (typeof aChild === 'string' && typeof bChild === 'string') { return compareStrings(aChild, bChild, locale); } return compareStrings(String(a), String(b), locale); }; /** * Compares two strings using `localeCompare`. * * Note: Uses numeric comparison if strings are numeric. */ const compareStrings = (a, b, locale = 'en') => { const isNumeric = !isNaN(parseFloat(a)) && !isNaN(parseFloat(b)); return a.localeCompare(b, locale, { numeric: isNumeric }); }; // TODO: Should `SortRowParams` in // packages/react/src/components/DataTable/state/sorting.ts be used here? /** * Sorts table rows based on the provided column key and direction. */ const sortRows = ({ rowIds, cellsById, sortDirection, key, locale = 'en', sortRow = defaultSortRow }) => rowIds.slice().sort((a, b) => { const cellA = cellsById[cells.getCellId(a, key)]; const cellB = cellsById[cells.getCellId(b, key)]; return sortRow(cellA?.value, cellB?.value, { key, sortDirection, sortStates: sortStates.sortStates, locale, compare, rowIds: [a, b] }); }); /** * Sorts table rows based on the sort direction. */ const defaultSortRow = (cellA, cellB, { sortDirection, sortStates, locale }) => { if (sortDirection === sortStates.ASC) { return compare(cellA, cellB, locale); } return compare(cellB, cellA, locale); }; exports.compare = compare; exports.defaultSortRow = defaultSortRow; exports.sortRows = sortRows;