Skip to content

Commit

Permalink
Add assoc-in-some function
Browse files Browse the repository at this point in the history
  • Loading branch information
erikcc02 committed Aug 7, 2023
1 parent c5e6e39 commit 89f85ac
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/medley/core.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@
m
(persistent! acc))))))

(defn assoc-in-some
"Associates a value v in a nested associative structure provided that v is not nil."
[m k v]
(cond-> m (some? v) (assoc-in k v)))

(defn update-existing
"Updates a value in a map given a key and a function, if and only if the key
exists in the map. See: `clojure.core/update`."
Expand Down
8 changes: 8 additions & 0 deletions test/medley/core_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,14 @@
(is (nil? (m/assoc-some nil :a nil)))
(is (nil? (m/assoc-some nil :a nil :b nil))))

(deftest test-assoc-in-some
(is (= (m/assoc-in-some {:a 1 :b {:c 2}} [:b] 3) {:a 1 :b 3}))
(is (= (m/assoc-in-some [{:a 1} {:a 2}] [1 :a] 3) [{:a 1} {:a 3}]))
(is (= (m/assoc-in-some [{:a 1} {:a 2}] [1 :a] false) [{:a 1} {:a false}]))
(is (= (m/assoc-in-some [{:a 1} {:a 2}] [1 :a] nil) [{:a 1} {:a 2}]))
(is (nil? (m/assoc-in-some nil :a nil)))
(is (nil? (m/assoc-in-some nil [:a :b] nil))))

(deftest test-update-existing
(is (= (m/update-existing {:a 1} :a inc) {:a 2}))
(is (= (m/update-existing {:a 1 :b 2} :a inc) {:a 2 :b 2}))
Expand Down

0 comments on commit 89f85ac

Please sign in to comment.