Skip to content

Commit 89f85ac

Browse files
committed
Add assoc-in-some function
1 parent c5e6e39 commit 89f85ac

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

src/medley/core.cljc

+5
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,11 @@
5353
m
5454
(persistent! acc))))))
5555

56+
(defn assoc-in-some
57+
"Associates a value v in a nested associative structure provided that v is not nil."
58+
[m k v]
59+
(cond-> m (some? v) (assoc-in k v)))
60+
5661
(defn update-existing
5762
"Updates a value in a map given a key and a function, if and only if the key
5863
exists in the map. See: `clojure.core/update`."

test/medley/core_test.cljc

+8
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,14 @@
3333
(is (nil? (m/assoc-some nil :a nil)))
3434
(is (nil? (m/assoc-some nil :a nil :b nil))))
3535

36+
(deftest test-assoc-in-some
37+
(is (= (m/assoc-in-some {:a 1 :b {:c 2}} [:b] 3) {:a 1 :b 3}))
38+
(is (= (m/assoc-in-some [{:a 1} {:a 2}] [1 :a] 3) [{:a 1} {:a 3}]))
39+
(is (= (m/assoc-in-some [{:a 1} {:a 2}] [1 :a] false) [{:a 1} {:a false}]))
40+
(is (= (m/assoc-in-some [{:a 1} {:a 2}] [1 :a] nil) [{:a 1} {:a 2}]))
41+
(is (nil? (m/assoc-in-some nil :a nil)))
42+
(is (nil? (m/assoc-in-some nil [:a :b] nil))))
43+
3644
(deftest test-update-existing
3745
(is (= (m/update-existing {:a 1} :a inc) {:a 2}))
3846
(is (= (m/update-existing {:a 1 :b 2} :a inc) {:a 2 :b 2}))

0 commit comments

Comments
 (0)