weavejester / medley

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

Add the nil-or-empty? function #53

Closed alinposho closed 3 years ago

alinposho commented 3 years ago

I often find myself re-implementing the function that I just added in this PR, in my projects, so I thought others might benefit from it. A common use case is: needing to cleanup some hashmap's values, e.g.

(m/remove-vals empty? {:b nil
                       :c []
                       :d [1]
                       :e ""
                       :f "something"})
=> {:d [1], :f "something"}

But, I always have to remember to check for numbers in my collections, because, obviously:

(empty? 1)
=>IllegalArgumentException Don't know how to create ISeq from: java.lang.Long

What I'd like to be able to do is:

(m/remove-vals m/nil-or-empty? {:a 1
                                :b nil
                                :c []
                                :d [1]
                                :e ""
                                :f "something"})
=> {:a 1, :d [1], :f "something"}

Last but not least, I'm not that thrilled about the name for the function: nil-or-empty?, but empty? has been taken already...

Let me know what you think.

weavejester commented 3 years ago

This might be a function that's too specific in scope for Medley.

alinposho commented 3 years ago

Thanks for the feedback! I will close the PR. If anyone finds it useful, we can always re-open it.

P.S. Perhaps the name that I chose does not make the function justice: I think of it as an improved clojure.core/empty? that works with numbers, or any other object that you throw at it, whereas the standard lib empty? raises and exception for anything that is not a collection or nil.