Files
web/apps/scandic-web/components/HotelReservation/HotelCardListing/utils.ts
2025-03-07 09:08:19 +00:00

61 lines
2.1 KiB
TypeScript

import type { HotelData } from "@/types/components/hotelReservation/selectHotel/hotelCardListingProps"
import { SortOrder } from "@/types/components/hotelReservation/selectHotel/hotelSorter"
export function getSortedHotels({
hotels,
sortBy,
bookingCode,
}: {
hotels: HotelData[]
sortBy: string
bookingCode: string | null
}) {
const getPricePerNight = (hotel: HotelData): number =>
hotel.price?.member?.localPrice?.pricePerNight ??
hotel.price?.public?.localPrice?.pricePerNight ??
hotel.price?.redemption?.localPrice?.pointsPerNight ??
Infinity
const availableHotels = hotels.filter((hotel) => !!hotel?.price)
const unAvailableHotels = hotels.filter((hotel) => !hotel?.price)
const sortingStrategies: Record<
string,
(a: HotelData, b: HotelData) => number
> = {
[SortOrder.Name]: (a: HotelData, b: HotelData) =>
a.hotelData.name.localeCompare(b.hotelData.name),
[SortOrder.TripAdvisorRating]: (a: HotelData, b: HotelData) =>
(b.hotelData.ratings?.tripAdvisor.rating ?? 0) -
(a.hotelData.ratings?.tripAdvisor.rating ?? 0),
[SortOrder.Price]: (a: HotelData, b: HotelData) =>
getPricePerNight(a) - getPricePerNight(b),
[SortOrder.Distance]: (a: HotelData, b: HotelData) =>
a.hotelData.location.distanceToCentre -
b.hotelData.location.distanceToCentre,
}
const sortStrategy =
sortingStrategies[sortBy] ?? sortingStrategies[SortOrder.Distance]
if (bookingCode) {
const bookingCodeHotels = hotels.filter(
(hotel) =>
(hotel?.price?.public?.rateType?.toLowerCase() !== "regular" ||
hotel?.price?.member?.rateType?.toLowerCase() !== "regular") &&
!!hotel?.price
)
const regularHotels = hotels.filter(
(hotel) => hotel?.price?.public?.rateType?.toLowerCase() === "regular"
)
return [...bookingCodeHotels]
.sort(sortStrategy)
.concat([...regularHotels].sort(sortStrategy))
.concat([...unAvailableHotels].sort(sortStrategy))
}
return [...availableHotels]
.sort(sortStrategy)
.concat([...unAvailableHotels].sort(sortStrategy))
}