import { UTCDate } from "@date-fns/utc"; import { type FlightBundle } from "../../types/flights"; import { differenceInMinutes } from "date-fns"; export const getLayoverDuration = (bundle: FlightBundle) => { if (bundle.legs.length <= 1) { return { durationInMinutes: 0, formattedDuration: "0h 0m", }; } const durationInMinutes = bundle.legs .slice(0, -1) .reduce((acc, leg, index) => { const currentArrival = new UTCDate(leg.arrivalTime); const nextDeparture = new UTCDate(bundle.legs[index + 1].departTime); const layoverDuration = differenceInMinutes( nextDeparture, currentArrival ); return acc + Math.max(layoverDuration, 0); }, 0); const totalHours = Math.floor(durationInMinutes / 60); const minutes = durationInMinutes % 60; const days = Math.floor(totalHours / 24); const hours = totalHours % 24; const formattedDuration = days > 0 ? `${days}d ${hours}h ${minutes}m` : `${hours}h ${minutes}m`; return { durationInMinutes, formattedDuration, }; };