@carbon/react
Version:
React components for the Carbon Design System
83 lines (77 loc) • 2.18 kB
JavaScript
/**
* 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.
*/
import { getCellId } from './cells.js';
import { sortStates } from '../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.
*/
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
});
};
/**
* 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);
};
export { compare, defaultSortRow, sortRows };