import { SortOption } from "@scandic-hotels/trpc/enums/destinationFilterAndSort" import type { DestinationCityListItem } from "@scandic-hotels/trpc/types/destinationCityPage" import type { DestinationPagesHotelData } from "@scandic-hotels/trpc/types/hotel" import type { SortItem } from "@/types/components/destinationFilterAndSort" const HOTEL_SORTING_STRATEGIES: Partial< Record< SortOption, (a: DestinationPagesHotelData, b: DestinationPagesHotelData) => number > > = { [SortOption.Name]: function (a, b) { return a.hotel.name.localeCompare(b.hotel.name) }, [SortOption.TripAdvisorRating]: function (a, b) { return (b.hotel.tripadvisor ?? 0) - (a.hotel.tripadvisor ?? 0) }, [SortOption.Distance]: function (a, b) { return a.hotel.location.distanceToCentre - b.hotel.location.distanceToCentre }, } export function getFilteredHotels( hotels: DestinationPagesHotelData[], filters: string[] ) { if (filters.length) { return hotels.filter(({ hotel }) => filters.every((filter) => hotel.detailedFacilities.some((facility) => facility.slug === filter) ) ) } return hotels } export function getFilteredCities( filteredHotels: DestinationPagesHotelData[], cities: DestinationCityListItem[] ) { const filteredCityIdentifiers = filteredHotels.map( (hotel) => hotel.hotel.cityIdentifier ) return cities.filter( (city) => city.destination_settings.city && filteredCityIdentifiers.includes(city.destination_settings.city) ) } export function getSortedHotels( hotels: DestinationPagesHotelData[], sortOption: SortOption ) { const sortFn = HOTEL_SORTING_STRATEGIES[sortOption] return sortFn ? [...hotels].sort(sortFn) : hotels } export function isValidSortOption( value: string, sortItems: SortItem[] ): value is SortOption { return sortItems.map((item) => item.value).includes(value as SortOption) } export function getBasePathNameWithoutFilters( pathname: string, filterSlugs: string[] ) { const pathSegments = pathname.split("/") const filteredSegments = pathSegments.filter( (segment) => !filterSlugs.includes(segment) ) return filteredSegments.join("/") }