import { MatchableEntity } from "./types"; const DEFAULT_COLLECTION_KEYS = ["data", "items"]; export function resolveCollection( payload: unknown, preferredKeys: string[] = [] ): Record[] { if (typeof payload !== "object" || payload === null) { return []; } const obj = payload as Record; for (const key of [...preferredKeys, ...DEFAULT_COLLECTION_KEYS]) { const maybeCollection = obj?.[key]; if (Array.isArray(maybeCollection)) { return maybeCollection as Record[]; } } if (Array.isArray(payload)) { return payload as Record[]; } return []; } export function normalizeEntity( item: Record, primaryKey: string = "name", fallbackId: number ): MatchableEntity { const id = item.id ?? item._id ?? fallbackId; const name = (item[primaryKey] as string) || (item.name as string) || (item.title as string) || (item.email as string) || `Item ${id}`; return { id: String(id), name: String(name), ...item, }; } export function findActiveItem( sourceItems: MatchableEntity[], targetItems: MatchableEntity[], activeId: string ): MatchableEntity | undefined { return [...sourceItems, ...targetItems].find(item => item.id === activeId); } export function isItemInSource( sourceItems: MatchableEntity[], activeId: string ): boolean { return sourceItems.some(item => item.id === activeId); } export function addItemIfNotPresent( items: MatchableEntity[], item: MatchableEntity ): MatchableEntity[] { if (items.some(existingItem => existingItem.id === item.id)) { return items; } return [...items, item]; }