import { Task } from "@/model/task"; export const TaskSortDirection = { /** Oldest first (by created). */ ASC: "asc", /** Newest first (by created). */ DESC: "desc", } as const; export type TaskSortDirection = (typeof TaskSortDirection)[keyof typeof TaskSortDirection]; export const TASK_SORT_DIRECTION_ORDER: TaskSortDirection[] = [ TaskSortDirection.ASC, TaskSortDirection.DESC, ]; export function isTaskSortDirection( value: unknown, ): value is TaskSortDirection { return ( typeof value === "string" && (TASK_SORT_DIRECTION_ORDER as string[]).includes(value) ); } const SORT_ASC_SIGN = 1; const SORT_DESC_SIGN = -1; /** Sort by `created`. Default: oldest first. Does not mutate input. */ export function sortTasks( tasks: Task[], direction: TaskSortDirection = TaskSortDirection.ASC, ): Task[] { const sign = direction === TaskSortDirection.ASC ? SORT_ASC_SIGN : SORT_DESC_SIGN; return [...tasks].sort( (a, b) => sign * (new Date(a.created).getTime() - new Date(b.created).getTime()), ); }