From b0ee3a69f1f33d1a70a197f1a80a1b5246f3e261 Mon Sep 17 00:00:00 2001 From: Henry Hobbs Date: Sat, 25 May 2024 14:11:04 -0400 Subject: [PATCH] improved search by ranking results based on how early search terms appear in captions --- app/api/route.tsx | 28 +++++++++++++++++++--------- types/types.tsx | 1 + 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/app/api/route.tsx b/app/api/route.tsx index d2a3ce6..f58dd7b 100644 --- a/app/api/route.tsx +++ b/app/api/route.tsx @@ -14,14 +14,24 @@ export async function GET(request: NextRequest) { console.log(search) const cleanedSearch = search.replace(/[^a-zA-Z\s]/g, "").toLowerCase() const searchWords = cleanedSearch.split(/\s+/) - const filteredData = cardData.filter((card) => - searchWords.some((word) => - card.caption - ?.toLowerCase() - .split(/[^a-z]/) - .includes(word) - ) - ) - + const filteredData = cardData.filter((card) => { + let captionArray = card.caption?.toLowerCase().split(/[^a-z]/) + if (!captionArray) { + return false + } + const words = searchWords.filter((word) => captionArray.includes(word)) + if (words.length) { + card.rank = 999999 + for (const word of words) { + const index = captionArray.indexOf(word) + if (index && index < card.rank) { + card.rank = index + } + } + return true + } + return false + }) + filteredData.sort((a, b) => a.rank! - b.rank!) return Response.json(filteredData) } diff --git a/types/types.tsx b/types/types.tsx index 184404a..0d09443 100644 --- a/types/types.tsx +++ b/types/types.tsx @@ -5,5 +5,6 @@ export type CardType = { oracleId: string caption: string url?: string + rank?: number mediumImageUrl: string }