From 89f85ac417bb55a48d8209f862cf78e723ea9c4a Mon Sep 17 00:00:00 2001 From: Erik Correa Date: Mon, 7 Aug 2023 10:24:21 -0300 Subject: [PATCH] Add assoc-in-some function --- src/medley/core.cljc | 5 +++++ test/medley/core_test.cljc | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/src/medley/core.cljc b/src/medley/core.cljc index ed774b8..191adaf 100644 --- a/src/medley/core.cljc +++ b/src/medley/core.cljc @@ -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`." diff --git a/test/medley/core_test.cljc b/test/medley/core_test.cljc index ed46752..0523945 100644 --- a/test/medley/core_test.cljc +++ b/test/medley/core_test.cljc @@ -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}))