I want to check if every key given in a vector [:e [:a :b] [:c :d]] exists in a map.
{:e 2 :a {:b 3} :c {:d 5}}
I could write the following to check -
(def kvs {:e 2 :a {:b 3} :c {:d 5}})
(every? #(contains? kvs %) [[:e] [:a :b] [:c :d]])
However the above would fail as contains doesnt check the key one level deep like update-in does. How do I accomplish the above ?
An improvement on murtaza's basic approach, which also works when the map has nil or false values:
(defn contains-every? [m keyseqs]
(let [not-found (Object.)]
(not-any? #{not-found}
(for [ks keyseqs]
(get-in m ks not-found)))))
user> (contains-every? {:e 2 :a {:b 3} :c {:d 5}}
[[:e] [:a :b] [:c :d]])
true
user> (contains-every? {:e 2 :a {:b 3} :c {:d 5}}
[[:e] [:a :b] [:c :d :e]])
false
The following does it -
(every? #(get-in kvs %) [[:e] [:a :b] [:c :d]])
Any other answers also welcome !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With