@carbon/react
Version:
React components for the Carbon Design System
65 lines (63 loc) • 2.22 kB
JavaScript
/**
* Copyright IBM Corp. 2016, 2026
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import { sortStates } from "../state/sortStates.js";
import { getCellId } from "./cells.js";
//#region src/components/DataTable/tools/sorting.ts
/**
* Copyright IBM Corp. 2016, 2025
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* 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.
*/
const compare = (a, b, locale = "en") => {
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 });
};
/**
* 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[getCellId(a, key)];
const cellB = cellsById[getCellId(b, key)];
return sortRow(cellA?.value, cellB?.value, {
key,
sortDirection,
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);
};
//#endregion
export { sortRows };