Currently, I am working on converting the material UI sorting feature into a generic type. This will enable me to utilize it across various tables. However, I have hit a roadblock in implementing the stableSort
function, which relies on the getSorting
function.
Understanding stableSort:
const getSorting = <K extends keyof any>(
order: Order,
orderBy: K,
): (a: { [key in K]: number | string }, b: { [key in K]: number | string }) => number =>
order === "desc" ? (a, b) => desc(a, b, orderBy) : (a, b) => -desc(a, b, orderBy);
Exploring getSorting:
const stableSort = <T>(array: T[], cmp: (a: T, b: T) => number): T[] => {
const stabilizedThis = array.map((el, index) => [el, index] as [T, number]);
stabilizedThis.sort((a, b) => {
const order = cmp(a[0], b[0]);
if (order !== 0) return order;
return a[1] - b[1];
});
return stabilizedThis.map((el) => el[0]);
};
Below is an example of how these functions are utilized:
interface ITableProps<T> {
title: string;
rows: T[];
defaultOrderBy: keyof T;
order: Order;
}
const SomeTable = <T>(props: ITableProps<T>) => {
const rowsPerPage = 10;
const page = 0;
const handleRequestSort = <T>(property: keyof T): void => {
const isDesc = props.defaultOrderBy === property && props.order === "desc";
};
const sortingFunction = getSorting<keyof T>(props.order, props.defaultOrderBy);
const temp = stableSort<T>(props.rows, sortingFunction)
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
.map((row, index) => createTableRow(row, index))
}
Main issues faced:
The comparison
consistently returnsprops.defaultOrderBy === property
false
. While both are of typekeyof T
, they are generically defined and should not have matching values. You can view a simplified version of this issue in the typescript playground.An error arises during the invocation of the
stableSort
function. (This has been resolved, refer to my solution below)