Skip to content

Commit 370afdc

Browse files
committed
feat(dict): add counterpart to dict:update!, dict:update
1 parent 3d24371 commit 370afdc

2 files changed

Lines changed: 33 additions & 4 deletions

File tree

‎Dict.ark‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -257,14 +257,14 @@
257257
_new }))
258258

259259
# @brief Update a dictionary with (key, value) pairs from a second dictionary
260-
# @details The original dictionary is updated in place
260+
# @details The original dictionary is not modified
261261
# @param _D dictionary to update
262262
# @param _D2 second dictionary
263263
# =begin
264264
# (let data (dict "key" "value" "hello" "world"))
265265
# (let new (dict "key" "new value" 5 12))
266-
# (dict:update! data new)
267-
# (print data) # {key: new value, hello: world, 5: 12}
266+
# (print (dict:update data new)) # {key: new value, hello: world, 5: 12}
267+
# (print data) # {key: value, hello: world}
268268
# =end
269269
# @author https://github.com/SuperFola
270270
(let update! (fun (_D _D2) {
@@ -275,6 +275,27 @@
275275
(add _D _key (get _D2 _key))
276276
(set _i (+ 1 _i)) }) }))
277277

278+
# @brief Update a dictionary with (key, value) pairs from a second dictionary
279+
# @details The original dictionary is updated in place
280+
# @param _D dictionary to update
281+
# @param _D2 second dictionary
282+
# =begin
283+
# (let data (dict "key" "value" "hello" "world"))
284+
# (let new (dict "key" "new value" 5 12))
285+
# (dict:update! data new)
286+
# (print data) # {key: new value, hello: world, 5: 12}
287+
# =end
288+
# @author https://github.com/SuperFola
289+
(let update (fun (_D _D2) {
290+
(mut _i 0)
291+
(mut _copy (copy _D))
292+
(let _keys (keys _D2))
293+
(while (< _i (len _keys)) {
294+
(let _key (@ _keys _i))
295+
(add _copy _key (get _D2 _key))
296+
(set _i (+ 1 _i)) })
297+
_copy }))
298+
278299
(let _valAsJson (fun (_val)
279300
(if (= "Dict" (type _val))
280301
(asJson _val)

‎tests/dict-tests.ark‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,4 +197,12 @@
197197
(test:eq (len d2) 2)
198198
(test:eq (dict:get d2 "a") 5)
199199
(test:eq (dict:get d2 "c") 3)
200-
(test:eq (len empty) 0) }) })
200+
(test:eq (len empty) 0) })
201+
202+
(test:case "update" {
203+
(mut base_dict (dict
204+
"a" 1
205+
"b" 2
206+
"c" 3))
207+
(test:eq (dict:update base_dict (dict "a" 12 "d" 5)) (dict "a" 12 "b" 2 "c" 3 "d" 5))
208+
(test:eq base_dict (dict "a" 1 "b" 2 "c" 3)) }) })

0 commit comments

Comments
 (0)