feat: SW-276 Optimized code

This commit is contained in:
Hrishikesh Vaipurkar
2024-10-11 18:32:56 +02:00
parent d52a347904
commit b8f7f91fb4
7 changed files with 58 additions and 31 deletions

View File

@@ -3,6 +3,8 @@
import { produce } from "immer"
import { create } from "zustand"
import { createSelectors } from "./utils"
import { BedTypeEnum } from "@/types/components/bookingWidget/enums"
import { Child } from "@/types/components/bookingWidget/guestsRoomsPicker"
@@ -20,17 +22,17 @@ interface GuestsRooms {
increaseAdults: (roomIndex: number) => void
decreaseAdults: (roomIndex: number) => void
increaseChildren: (roomIndex: number) => void
decreaseChildren: (roomIndex: number) => void
decreaseChildren: (roomIndex: number) => Child[]
updateChildAge: (age: number, roomIndex: number, childIndex: number) => void
updateChildBed: (bed: number, roomIndex: number, childIndex: number) => void
increaseChildInAdultsBed: (roomIndex: number) => void
decreaseChildInAdultsBed: (roomIndex: number) => void
increaseRoom: () => void
decreaseRoom: (roomIndex: number) => void
setIsValidated: (status: boolean) => void
setIsValidated: (isValidated: boolean) => void
}
export const useGuestsRoomsStore = create<GuestsRooms>((set, get) => ({
export const useGuestsRoomsStoreBase = create<GuestsRooms>((set, get) => ({
rooms: [
{
adults: 1,
@@ -81,7 +83,7 @@ export const useGuestsRoomsStore = create<GuestsRooms>((set, get) => ({
state.childCount = state.childCount + 1
})
),
decreaseChildren: (roomIndex) =>
decreaseChildren: (roomIndex) => {
set(
produce((state: GuestsRooms) => {
const roomChildren = state.rooms[roomIndex].children
@@ -95,7 +97,9 @@ export const useGuestsRoomsStore = create<GuestsRooms>((set, get) => ({
state.rooms[roomIndex].children.pop()
state.childCount = state.childCount - 1
})
),
)
return get().rooms[roomIndex].children
},
updateChildAge: (age, roomIndex, childIndex) =>
set(
produce((state: GuestsRooms) => {
@@ -138,5 +142,7 @@ export const useGuestsRoomsStore = create<GuestsRooms>((set, get) => ({
state.rooms.splice(roomIndex, 1)
})
),
setIsValidated: (status) => set(() => ({ isValidated: status })),
setIsValidated: (isValidated) => set(() => ({ isValidated })),
}))
export const useGuestsRoomsStore = createSelectors(useGuestsRoomsStoreBase)

17
stores/utils.ts Normal file
View File

@@ -0,0 +1,17 @@
import { StoreApi, UseBoundStore } from "zustand"
type WithSelectors<S> = S extends { getState: () => infer T }
? S & { use: { [K in keyof T]: () => T[K] } }
: never
export const createSelectors = <S extends UseBoundStore<StoreApi<object>>>(
_store: S
) => {
let store = _store as WithSelectors<typeof _store>
store.use = {}
for (let k of Object.keys(store.getState())) {
;(store.use as any)[k] = () => store((s) => s[k as keyof typeof s])
}
return store
}