mirror of
https://github.com/roc-lang/roc.git
synced 2025-08-04 04:08:19 +00:00
Merge pull request #4273 from cjduncana/dict-update
Add the `update` function to the `Dict` module
This commit is contained in:
commit
860d8b41f1
2 changed files with 30 additions and 0 deletions
|
@ -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 ->
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue