import type { Book } from '../shared/types.ts'; import { compareShelf } from '../shared/shelf.ts'; export interface BookState { byId: Record } export type BookAction = | { type: 'upsert'; book: Book } | { type: 'delete'; id: number } | { type: 'replace'; books: Book[] }; export const emptyState: BookState = { byId: {} }; export function reduce(state: BookState, action: BookAction): BookState { switch (action.type) { case 'upsert': return { byId: { ...state.byId, [action.book.id]: action.book } }; case 'delete': { const byId = { ...state.byId }; delete byId[action.id]; return { byId }; } case 'replace': { const byId: Record = {}; for (const b of action.books) byId[b.id] = b; return { byId }; } } } export { compareShelf }; export function shelfOrder(state: BookState): Book[] { return Object.values(state.byId).sort(compareShelf); }