Skip to content

Instantly share code, notes, and snippets.

@joakimk
Last active September 22, 2016 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joakimk/5210c0bc9c65eb10d343cd5c0290b71d to your computer and use it in GitHub Desktop.
Save joakimk/5210c0bc9c65eb10d343cd5c0290b71d to your computer and use it in GitHub Desktop.
One attempt at simple adding or updating a record in a list in Elm
import UpdateList exposing (addOrUpdateById)
update msg model =
case msg of
NewOrUpdatedItem item ->
({model | items = model.items |> addOrUpdateById item}, Cmd.none)
module UpdateList exposing (addOrUpdateById)
type alias Identifyable a = { a | id : Int }
addOrUpdateById : Identifyable a -> List (Identifyable a) -> List (Identifyable a)
addOrUpdateById record list =
if isNewRecord record list then
List.concat [ [ record ], list ]
else
List.map (updateById record) list
updateById : Identifyable a -> Identifyable a -> Identifyable a
updateById record r =
if r.id == record.id then
record
else
r
isNewRecord : Identifyable a -> List (Identifyable a) -> Bool
isNewRecord record list =
not
(
list
|> List.map (\r -> r.id)
|> List.member record.id
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment