Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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