Return the first non empty/blank value?

(first (filter (complement clojure.string/blank?) ["" "a" "b"]))

Edit: As pointed out in the comments, (filter (complement p) ...) can be rewritten as (remove p ...):

(first (remove clojure.string/blank? ["" "a" "b"]))

If you are so lucky to have "empty values" represented by nil and/or false you could use:

(or nil false "2" "3")

Which would return "2".

An equivalent to your JavaScript example would be:

(let [final (or path callback "")]
  (println final))

This is how you would use the some function:

(some #(when-not (empty? %) %) ["" "foo" ""])
"foo"
(some #(when-not (empty? %) %) ["bar" "foo" ""])
"bar"

As others have pointed out, filter is another option:

(first (filter #(not (empty? %)) ["" "" "foo"])
"foo"

A third option would be to use recursion:

(defn first-non-empty [& x]
  (let [[y & z] x]
    (if (not (empty? y))
      y
      (when z (recur z)))))

(first-non-empty "" "bar" "")
"bar"
(first-non-empty "" "" "foo")
"foo"
(first-non-empty "" "" "")
nil

I used empty? instead of blank? to save on typing, but the only difference should be how whitespace is handled.

Tags:

Clojure