All files / src/lib/seo search-shortcut.ts

100% Statements 15/15
100% Branches 10/10
100% Functions 4/4
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26              65x             8x 8x   7x 18x 10x 13x 7x   2x    
/**
 * When a search names a room category or a live city outright ("kitchen",
 * "Pune"), the empty state links straight to that page instead of echoing
 * the term back as a suggestion.
 */
export type SearchShortcut = { kind: "room" | "city"; name: string; href: string };
 
const norm = (s: string) => s.trim().toLowerCase().replace(/[_-]+/g, " ").replace(/\s+/g, " ");
 
export function searchShortcut(
	q: string,
	rooms: readonly { value: string; label: string }[],
	cities: readonly { slug: string; publicName: string }[],
): SearchShortcut | null {
	const k = norm(q);
	if (k.length < 2) return null;
	// "kitchens" means "kitchen"; try the term as typed first.
	for (const term of [k, k.replace(/s$/, "")]) {
		const room = rooms.find((r) => norm(r.label) === term || norm(r.value) === term);
		if (room) return { kind: "room", name: room.label, href: `/rooms/${room.value}` };
		const city = cities.find((c) => norm(c.publicName) === term || norm(c.slug) === term);
		if (city) return { kind: "city", name: city.publicName, href: `/interiors/${city.slug}` };
	}
	return null;
}