google-handwriting-api-elm/src/ResultFiltering.elm

67 lines
2.0 KiB
Elm
Raw Normal View History

2021-10-11 22:32:48 +02:00
module ResultFiltering exposing (FilterState, Filter, Msg(..), initFilterState, filterUpdate, postProcess)
import Regex as R
import Tuple exposing (first, second)
import List exposing (filter, head)
import Maybe as M
import List exposing (foldl)
type alias CharRange = String
type alias Filter = (Bool, CharRange)
type alias FilterState = {
kanji : Filter
, hiragana : Filter
, katakana : Filter
, all : Filter
}
initFilterState : FilterState
initFilterState = {
kanji = (True, "-")
, hiragana = (True, "")
, katakana = (True, "-")
, all = (False, ".+")
}
toggleFilterState : Filter -> Filter
toggleFilterState (b, r) = (not b, r)
type Msg = Kanji
| Hiragana
| Katakana
| All
| Reset
{-| Handle updates regarding the filter -}
filterUpdate : Msg -> FilterState -> FilterState
filterUpdate msg filters=
case msg of
Kanji -> { filters | kanji = toggleFilterState filters.kanji }
Hiragana -> { filters | hiragana = toggleFilterState filters.hiragana }
Katakana -> { filters | katakana = toggleFilterState filters.katakana }
All -> { filters | all = toggleFilterState filters.all }
Reset -> initFilterState
{-| Filter out different kanji based on the current filters -}
postProcess : List String -> FilterState -> List String
postProcess xs filterState =
let
regex =
(if first filterState.all
then second filterState.all
else [ filterState.kanji, filterState.hiragana, filterState.katakana ]
|> List.map (\(b,r) -> if b then r else "")
|> foldl (++) ""
|> \s -> "^[" ++ s ++ "]*$")
|> R.fromString
|> M.withDefault R.never
matchesRegex : String -> Bool
matchesRegex x = head (R.find regex x)
|> Maybe.map .match
|> Maybe.withDefault ""
|> (==) x
in
filter matchesRegex xs