From 1b390b9a7ae5f53a3349f401341a1dd489992fb4 Mon Sep 17 00:00:00 2001 From: Dietrich Date: Sat, 19 Feb 2022 12:42:10 -0800 Subject: [PATCH] auto suggest --- package.json | 4 ++-- src/components/Guesser.tsx | 42 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index c6f3e2c..3bcb105 100644 --- a/package.json +++ b/package.json @@ -54,7 +54,7 @@ "@types/react-transition-group": "^4.4.4", "autoprefixer": "^10.4.2", "postcss": "^8.4.5", - "tailwindcss": "^3.0.15", - "source-map-explorer": "^2.5.2" + "source-map-explorer": "^2.5.2", + "tailwindcss": "^3.0.15" } } diff --git a/src/components/Guesser.tsx b/src/components/Guesser.tsx index 84e266b..0473ab6 100644 --- a/src/components/Guesser.tsx +++ b/src/components/Guesser.tsx @@ -5,6 +5,8 @@ import { Message } from "./Message"; import { polygonDistance } from "../util/distance"; import alternateNames from "../data/alternate_names.json"; const countryData: Country[] = require("../data/country_data.json").features; +const minGuessLength = 2; +const suggestionLimit = 3; type Props = { guesses: Country[]; @@ -17,6 +19,24 @@ export default function Guesser({ guesses, setGuesses, win, setWin }: Props) { const [guessName, setGuessName] = useState(""); const [error, setError] = useState(""); + function getSuggestions(value: string) { + const inputValue = value.trim().toLowerCase(); + const inputLength = inputValue.length; + + if (inputLength >= minGuessLength) { + let suggestions: Country[] = []; + suggestions = countryData.filter(country => { + const countryName = country.properties.NAME.toLowerCase(); + if (countryName !== inputValue) { + return countryName.slice(0, inputLength) === inputValue; + } + return []; + }); + return suggestions.slice(0,suggestionLimit); + } + return []; + } + function findCountry(countryName: string, list: Country[]) { return list.find((country) => { const { NAME, NAME_LONG, ABBREV, ADMIN, BRK_NAME, NAME_SORT } = @@ -76,14 +96,14 @@ export default function Guesser({ guesses, setGuesses, win, setWin }: Props) {
+ + +
+ {getSuggestions(guessName).map(country => { + return ( +
{setGuessName(country.properties.NAME)}} + >{country.properties.NAME}
+ ) + })} +