Skip to content

Commit ca9cc3a

Browse files
committed
feat(dict): ARK-276, add dict:updateOrDefault
1 parent 15ea724 commit ca9cc3a

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

Dict.ark

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,23 @@
2222
# @author https://github.com/SuperFola
2323
(let add (fun (_D _key _value) (builtin__dict:add _D _key _value)))
2424

25-
# @brief
25+
# @brief Updates an entry or create it from a default value
26+
# @details The dictionary is modified in place
27+
# @param _D dictionary
28+
# @param _key key to create or update
29+
# @param _f function called with the existing value, returning an updated value
30+
# @param _default default value to use if the key doesn't exist
31+
# =begin
32+
# (let data (dict "count" 0))
33+
# (dict:updateOrDefault data "count" (fun (c) (+ c 1)) 1) # count = 1
34+
# =end
35+
# @author https://github.com/SuperFola
36+
(let updateOrDefault (fun (_D _key _f _default)
37+
(if (contains _D _key)
38+
(add _D _key (_f (get _D _key)))
39+
(add _D _key _default))))
40+
41+
# @brief Checks if the dictionary has a given key
2642
# @param _D dictionary
2743
# =begin
2844
# (let data (dict "key" "value"))

tests/dict-tests.ark

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,16 @@
8282
(dict:add d "key" 2)
8383
(test:eq (dict:get d "key") 2) })
8484

85+
(test:case "updateOrDefault" {
86+
(let d5 (dict))
87+
(test:eq (dict:get d5 "count") nil)
88+
89+
(dict:updateOrDefault d5 "count" (fun (c) (+ 1 c)) 1)
90+
(test:eq (dict:get d5 "count") 1)
91+
92+
(dict:updateOrDefault d5 "count" (fun (c) (+ 1 c)) 1)
93+
(test:eq (dict:get d5 "count") 2) })
94+
8595
(test:case "remove" {
8696
(test:eq (dict:size d) 7)
8797
(dict:remove d "test")

0 commit comments

Comments
 (0)