import { dt } from "@scandic-hotels/common/dt" import type { Stay } from "@scandic-hotels/trpc/routers/user/output" export interface StaysByYear { year: number stays: Stay[] } /** * Groups stays by year based on checkinDate. * @returns an array sorted by year in descending order (most recent first). */ export function groupStaysByYear(stays: Stay[]): 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]) => yearB - yearA) .map(([year, stays]) => ({ year, stays })) }