diff --git a/src/medley/core.cljc b/src/medley/core.cljc index 304a83f..ae2fb33 100644 --- a/src/medley/core.cljc +++ b/src/medley/core.cljc @@ -40,6 +40,19 @@ (defn- assoc-some-transient! [m k v] (if (nil? v) m (assoc! m k v))) +(defn assoc-conj + "Associate a key with a non-nil value in a map. If the key already exists + in the map, a vector of values is associated with the key." + [map key val] + (if (nil? val) + map + (assoc map key + (if-let [cur (get map key)] + (if (vector? cur) + (conj cur val) + [cur val]) + val)))) + (defn assoc-some "Associates a key k, with a value v in a map m, if and only if v is not nil." ([m k v] diff --git a/test/medley/core_test.cljc b/test/medley/core_test.cljc index ed46752..67eb040 100644 --- a/test/medley/core_test.cljc +++ b/test/medley/core_test.cljc @@ -24,6 +24,13 @@ (is (= (m/dissoc-in {:a 1} []) {:a 1}))) +(deftest test-assoc-conj + (is (= (m/assoc-conj nil :a 1) {:a 1})) + (is (= (m/assoc-conj nil :a nil) nil)) + (is (= (m/assoc-conj {:a nil} :a 1) {:a 1})) + (is (= (m/assoc-conj {:a 1} :a 2) {:a [1 2]})) + (is (= (m/assoc-conj {:a 1} :a nil) {:a 1}))) + (deftest test-assoc-some (is (= (m/assoc-some {:a 1} :b 2) {:a 1 :b 2})) (is (= (m/assoc-some {:a 1} :b nil) {:a 1}))