Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add variation of ring-codec assoc-conj #87

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
13 changes: 13 additions & 0 deletions src/medley/core.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
7 changes: 7 additions & 0 deletions test/medley/core_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -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}))
Expand Down