export interface StackSortPreference { columnId: C; direction: "asc" | "desc"; } export interface IndexedStackRow { item: T; itemIndex: number; } export function sortStackItems( items: T[], preference: StackSortPreference, compare: (a: T, b: T, columnId: C) => number, tieBreak: (a: T, b: T) => number = () => 0, ): T[] { const direction = preference.direction === "asc" ? 1 : -1; return [...items].sort((a, b) => { const primary = compare(a, b, preference.columnId) * direction; return primary !== 0 ? primary : tieBreak(a, b); }); } export function sortIndexedStackRows( items: T[], preference: StackSortPreference, compare: (a: IndexedStackRow, b: IndexedStackRow, columnId: C) => number, ): Array> { return sortStackItems( items.map((item, itemIndex) => ({ item, itemIndex })), preference, compare, (a, b) => a.itemIndex - b.itemIndex, ); } export function activeStackIndex(length: number, selectedIndex: number): number { return selectedIndex >= 0 ? selectedIndex : length > 0 ? 0 : -1; }