-
-
Notifications
You must be signed in to change notification settings - Fork 228
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
enhance(search): util to match region names in search query
- Loading branch information
1 parent
a7c83b9
commit 7ced993
Showing
2 changed files
with
25 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -35,6 +35,7 @@ export { | |
isTouchDevice, | ||
type Json, | ||
csvEscape, | ||
escapeRegExp, | ||
urlToSlug, | ||
trimObject, | ||
fetchText, | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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[] | ||
} |