File tree Expand file tree Collapse file tree 2 files changed +27
-1
lines changed
Expand file tree Collapse file tree 2 files changed +27
-1
lines changed Original file line number Diff line number Diff line change 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"))
Original file line number Diff line number Diff line change 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")
You can’t perform that action at this time.
0 commit comments