Merge pull request #4273 from cjduncana/dict-update

Add the `update` function to the `Dict` module
This commit is contained in:
Richard Feldman 2022-10-10 02:37:42 -07:00 committed by GitHub
commit 860d8b41f1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 0 deletions

View file

@ -9,6 +9,7 @@ interface Dict
insert,
len,
remove,
update,
contains,
keys,
values,
@ -122,6 +123,34 @@ remove = \@Dict list, key ->
|> List.dropLast
|> @Dict
## Insert or remove a value in a Dict based on its presence
update :
Dict k v,
k,
([Present v, Missing] -> [Present v, Missing])
-> Dict k v
update = \dict, key, alter ->
possibleValue =
get dict key
|> Result.map Present
|> Result.withDefault Missing
when alter possibleValue is
Present value -> insert dict key value
Missing -> remove dict key
## Internal for testing only
alterValue : [Present Bool, Missing] -> [Present Bool, Missing]
alterValue = \possibleValue ->
when possibleValue is
Missing -> Present Bool.false
Present value if Bool.not value -> Present Bool.true
Present _ -> Missing
expect update empty "a" alterValue == single "a" Bool.false
expect update (single "a" Bool.false) "a" alterValue == single "a" Bool.true
expect update (single "a" Bool.true) "a" alterValue == empty
contains : Dict k v, k -> Bool
contains = \@Dict list, needle ->
step = \_, Pair key _val ->