Skip to content
Snippets Groups Projects
Unverified Commit 7331061b authored by metamben's avatar metamben Committed by GitHub
Browse files

Allow multiple key-value pairs for assoc-default (#31130)

parent 0ed94c99
No related branches found
No related tags found
No related merge requests found
......@@ -787,8 +787,17 @@
(defn assoc-default
"Called like `(assoc m k v)`, this does [[assoc]] iff `m` does not contain `k`
and `v` is not nil."
[m k v]
(if (or (nil? v) (contains? m k))
m
(assoc m k v)))
and `v` is not nil. Can be called with multiple key value pairs. If a key occurs
more than once, only the first occurrence with a non-nil value is used."
([m k v]
(if (or (nil? v) (contains? m k))
m
(assoc m k v)))
([m k v & kvs]
(let [ret (assoc-default m k v)]
(if kvs
(if (next kvs)
(recur ret (first kvs) (second kvs) (nnext kvs))
(throw (ex-info "assoc-default expects an even number of key-values"
{:kvs kvs})))
ret))))
......@@ -391,3 +391,23 @@
(is (= {:foo false}
(u/assoc-dissoc {:foo "bar"} :foo false))
"false should be assoc'd")))
(deftest ^:parallel assoc-default-test
(testing "nil map"
(is (= {:x 0}
(u/assoc-default nil :x 0))))
(testing "empty map"
(is (= {0 :x}
(u/assoc-default {} 0 :x))))
(testing "existing key"
(is (= {:x 0}
(u/assoc-default {:x 0} :x 1))))
(testing "nil value"
(is (= {:x 0}
(u/assoc-default {:x 0} :y nil))))
(testing "multiple defaults"
(is (= {:x nil, :z 1}
(u/assoc-default {:x nil} :x 0 :y nil :z 1))))
(testing "multiple defaults for the same key"
(is (= {:x nil, :y 1, :z 2}
(u/assoc-default {:x nil} :x 0, :y nil, :y 1, :z 2, :x 3, :z 4)))))
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment