import { dt } from "@scandic-hotels/common/dt" import type { Stay } from "@scandic-hotels/trpc/routers/user/output" export interface StaysByYear { year: number stays: Stay[] } type SortOrder = "asc" | "desc" /** * Groups stays by year based on checkinDate. * @param stays - Array of stays to group * @param sortOrder - Sort order for years: "desc" (most recent first) or "asc" (earliest first). Defaults to "desc". * @returns an array sorted by year in the specified order. */ export function groupStaysByYear( stays: Stay[], sortOrder: SortOrder = "desc" ): StaysByYear[] { const groupedMap = new Map() for (const stay of stays) { const year = dt(stay.attributes.checkinDate).year() if (!groupedMap.has(year)) { groupedMap.set(year, []) } groupedMap.get(year)!.push(stay) } return Array.from(groupedMap.entries()) .sort(([yearA], [yearB]) => sortOrder === "asc" ? yearA - yearB : yearB - yearA ) .map(([year, stays]) => ({ year, stays })) }