Skip to content

Commit

Permalink
enhance(search): util to match region names in search query
Browse files Browse the repository at this point in the history
  • Loading branch information
marcelgerber committed Apr 11, 2024
1 parent a7c83b9 commit 7ced993
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/@ourworldindata/utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export {
isTouchDevice,
type Json,
csvEscape,
escapeRegExp,
urlToSlug,
trimObject,
fetchText,
Expand Down
24 changes: 24 additions & 0 deletions site/search/SearchUtils.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import {
Region,
getRegionByNameOrVariantName,
regions,
escapeRegExp,
} from "@ourworldindata/utils"

const allCountryNamesAndVariants = regions.flatMap((c) => [
c.name,
...(("variantNames" in c && c.variantNames) || []),
])

// A RegExp that matches any country, region and variant name. Case-independent.
const regionNameRegex = new RegExp(
`\\b(${allCountryNamesAndVariants.map(escapeRegExp).join("|")})\\b`,
"gi"
)

export const extractRegionNamesFromSearchQuery = (query: string) => {
const matches = query.matchAll(regionNameRegex)
const regionNames = Array.from(matches, (match) => match[0])
if (regionNames.length === 0) return null
return regionNames.map(getRegionByNameOrVariantName) as Region[]
}

0 comments on commit 7ced993

Please sign in to comment.