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);
}
