Skip to content

Instantly share code, notes, and snippets.

@TheSeamau5
Created May 16, 2016 07:11
Show Gist options
  • Save TheSeamau5/7a3b0ef44e538afb1efe94cc8c977ef4 to your computer and use it in GitHub Desktop.
Save TheSeamau5/7a3b0ef44e538afb1efe94cc8c977ef4 to your computer and use it in GitHub Desktop.
Autosuggest with caching in Elm
import Dict exposing (Dict)
import Html exposing (Html, div, text, input, ul, li)
import Html.App as Html
import Html.Events exposing (..)
import Task exposing (Task)
import String
---------------------------
main =
Html.program
{ init = init
, view = view viewSuggestion
, update = update getSuggestions
, subscriptions = subscriptions
}
---------------------------
data : List String
data =
[ "Arizona"
, "Arkansas"
, "California"
, "Colorado"
, "Delaware"
, "Florida"
, "New York"
, "New Jersey"
, "Pennsylvania"
, "Texas" ]
getSuggestions : String -> Task String (List String)
getSuggestions query =
if String.trim query == "" then Task.fail "No Query" else
data
|> List.filter (String.startsWith query)
|> Task.succeed
---------------------------
type alias Model suggestion =
{ cache : Dict String (List suggestion)
, query : String
}
type Msg suggestion
= Query String
| AddSuggestions String (List suggestion)
| NoOp
init : (Model suggestion, Cmd (Msg suggestion))
init =
( { cache = Dict.empty
, query = ""
}
, Cmd.none )
subscriptions : Model suggestion -> Sub (Msg suggestion)
subscriptions model =
Sub.none
update : (String -> Task error (List suggestion))
-> Msg suggestion
-> Model suggestion
-> (Model suggestion, Cmd (Msg suggestion))
update getSuggestions msg model =
case msg of
Query query ->
let cmd =
Task.perform (always NoOp) (AddSuggestions query) (getSuggestions query)
in
( { model | query = query }
, cmd )
AddSuggestions query suggestions ->
( { model | cache = Dict.insert query suggestions model.cache }
, Cmd.none )
NoOp ->
( model
, Cmd.none )
view : (suggestion -> Html (Msg suggestion)) -> Model suggestion -> Html (Msg suggestion)
view viewSuggestion model =
let suggestions =
case Dict.get model.query model.cache of
Nothing ->
[]
Just results ->
results
in
div
[]
[ input
[ onInput Query ]
[ ]
, div
[]
( List.map viewSuggestion suggestions ) ]
viewSuggestion : String -> Html a
viewSuggestion suggestion =
div
[]
[ text suggestion ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment