Files
web/apps/scandic-web/stores/destination-data/helper.ts
Erik Tiekstra 948c86479a feat(BOOK-54): Adjusted filter functionality to save filters as query parameters instead of paths
* feat(BOOK-54): Destination filters now matching on id instead of slug in preparation for filters from Contentstack

Approved-by: Chuma Mcphoy (We Ahead)
2025-09-18 13:03:01 +00:00

88 lines
2.2 KiB
TypeScript

import {
type HotelFilter,
type HotelListingHotelData,
type HotelSortItem,
HotelSortOption,
} from "@scandic-hotels/trpc/types/hotel"
import type { DestinationCityListItem } from "@scandic-hotels/trpc/types/destinationCityPage"
const HOTEL_SORTING_STRATEGIES: Partial<
Record<
HotelSortOption,
(a: HotelListingHotelData, b: HotelListingHotelData) => number
>
> = {
[HotelSortOption.Name]: function (a, b) {
return a.hotel.name.localeCompare(b.hotel.name)
},
[HotelSortOption.TripAdvisorRating]: function (a, b) {
return (b.hotel.tripadvisor ?? 0) - (a.hotel.tripadvisor ?? 0)
},
[HotelSortOption.Distance]: function (a, b) {
return a.hotel.location.distanceToCentre - b.hotel.location.distanceToCentre
},
}
export function getFilteredHotels(
hotels: HotelListingHotelData[],
filters: HotelFilter[]
) {
if (filters.length) {
return hotels.filter(({ hotel }) =>
filters.every((filter) =>
hotel.detailedFacilities.some((facility) => facility.id === filter.id)
)
)
}
return hotels
}
export function getFilteredCities(
filteredHotels: HotelListingHotelData[],
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: HotelListingHotelData[],
sortOption: HotelSortOption
) {
const sortFn = HOTEL_SORTING_STRATEGIES[sortOption]
return sortFn ? [...hotels].sort(sortFn) : hotels
}
export function isValidSortOption(
value: string,
sortItems: HotelSortItem[]
): value is HotelSortOption {
return sortItems.map((item) => item.value).includes(value as HotelSortOption)
}
export function getBasePathNameWithoutFilters(
pathname: string,
filterSlugs: string[]
) {
if (!filterSlugs.length) {
return pathname
}
const lastSlashIndex = pathname.lastIndexOf("/")
const lastSegment = pathname.slice(lastSlashIndex + 1)
if (filterSlugs.includes(lastSegment)) {
return pathname.slice(0, lastSlashIndex) || "/"
}
return pathname
}