14 lines
518 B
TypeScript
14 lines
518 B
TypeScript
|
|
import type { SortState } from "./types";
|
||
|
|
|
||
|
|
export function sortRows<T>(rows: readonly T[], sort: SortState | undefined, value: (row: T, key: string) => string): T[] {
|
||
|
|
if (!sort) return [...rows];
|
||
|
|
const copy = [...rows];
|
||
|
|
copy.sort((a, b) => value(a, sort.key).localeCompare(value(b, sort.key)) * sort.dir);
|
||
|
|
return copy;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function nextSort(current: SortState | undefined, key: string): SortState {
|
||
|
|
if (current?.key === key) return { key, dir: current.dir === 1 ? -1 : 1 };
|
||
|
|
return { key, dir: 1 };
|
||
|
|
}
|