Files
web/apps/scandic-web/stores/hotel-listing-data/helper.ts
Erik Tiekstra fa7214cb58 Feat/SW-2271 hotel list filtering
* feat(SW-2271): Changes to hotel data types in preperation for filtering
* feat(SW-2271): Added filter and sort functionality

Approved-by: Matilda Landström
2025-07-04 09:27:20 +00:00

65 lines
1.6 KiB
TypeScript

import {
type HotelListingHotelData,
type HotelSortItem,
HotelSortOption,
} from "@scandic-hotels/trpc/types/hotel"
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)
},
}
export function getFilteredHotels(
hotels: HotelListingHotelData[],
filters: string[]
) {
if (filters.length) {
return hotels.filter(({ hotel }) =>
filters.every((filter) => {
const matchesFacility = hotel.detailedFacilities.some(
(facility) => facility.slug === filter
)
const matchesCountry =
hotel.countryCode.toLowerCase() === filter.toLowerCase()
return matchesFacility || matchesCountry
})
)
}
return hotels
}
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[]
) {
const pathSegments = pathname.split("/")
const filteredSegments = pathSegments.filter(
(segment) => !filterSlugs.includes(segment)
)
return filteredSegments.join("/")
}