weavejester / medley

A lightweight library of useful Clojure functions
Eclipse Public License 1.0
865 stars 66 forks source link

select-some #37

Closed borkdude closed 4 years ago

borkdude commented 5 years ago

Would you be interested in a PR for this?

(defn select-some
  "Like select-keys, but only selects when value is not nil."
  ([m ks]
   (persistent!
    (reduce (fn [acc k]
              (if-some [v (get m k)]
                (assoc! acc k v)
                acc))
            (transient {})
            ks))))

;; example:
(select-some {:a 1 :b nil :c 2 :d false} [:a :b :d]) ;; => {:a 1, :d false}
eraserhd commented 5 years ago

This library now has update-existing, so perhaps select-existing would be the better name?

borkdude commented 5 years ago

@eraserhd Hi Jason. existing might not be the right name for something which doesn't select keys that do exist, but are nil?

eraserhd commented 5 years ago

@borkdude Oh, I did fail to read closely. Carry on...

weavejester commented 5 years ago

I think the use-case for this might be a little narrow, but I'll take some time to consider this.

borkdude commented 5 years ago

@weavejester That makes sense. I "needed" this function here:

https://github.com/borkdude/clj-kondo/blob/34ee8736045e14e0b2e5109010793f48c1def132/src/clj_kondo/impl/analysis.clj#L13

where I wanted to merge with another map, where the other map is produced by select-keys, but I only want the extra keys if they are non-nil.

Maybe there's another good way to do it without using an elaborate (cond-> ...) .

weavejester commented 5 years ago

You could always write: (m/remove-vals nil? (select-keys m ks))