Files
koc-loop/lib/sort-utils.ts
2026-08-12 11:43:26 +08:00

27 lines
759 B
TypeScript

export type SortDirection = "asc" | "desc";
export function sortWithNullsLast<T>(
items: T[],
valueFor: (item: T) => number | null,
direction: SortDirection,
) {
return items
.map((item, index) => ({ item, index }))
.sort((left, right) => {
const leftValue = valueFor(left.item);
const rightValue = valueFor(right.item);
if (leftValue === null && rightValue === null) {
return left.index - right.index;
}
if (leftValue === null) return 1;
if (rightValue === null) return -1;
const compared = leftValue - rightValue;
return compared === 0
? left.index - right.index
: direction === "asc"
? compared
: -compared;
})
.map(({ item }) => item);
}