Question

I have this function :

(defn list-data [alist filter-text]
 (filter (fn [x] (if (nil? filter-text) true
                     (> (.indexOf x filter-text) -1))) alist))

(list-data ["Lion" "Zebra" "Buffalo" "Antelope"] "a")
;=> ("Zebra" "Buffalo")

Is there a more idiomatic way of writing this function and respect the fact that I don't want a case-sensitive filter, meaning I would like that (list-data ["Lion" "Zebra" "Buffalo" "Antelope"] "a")returns the following:

;=> ("Zebra" "Buffalo" "Antelope")

Thanks!

(This would need to work in a .cljs file)

Was it helpful?

Solution

In Clojure itself you would normally do this with a regular expression. In Java regular expressions you can do this by giving in a flag for case-insensitivity for the match you want to make, or at the start of the regex for global case-insensitivity:

  (filter #(re-find #"(?i)a" %)
          ["Lion" "Zebra" "Buffalo" "Antelope"])

Pure Javascript regular expressions only support global flags. They are given in as string as the second parameter to the regex constructor:

  (filter #(re-find (js/RegExp. "a" "i") %)
          ["Lion" "Zebra" "Buffalo" "Antelope"])

However, as convenience and to keep the regexes between Java and Javascript similar, the Clojurescript reader translates global java style flags (those at the start of the regex) to their Javascript global equivalent.

So the first example works in Clojurescript as well. Be aware though that non-global flags won't work in Clojurescript where they would work in Clojure.

OTHER TIPS

(defn list-data [alist filter-text]
 (if-let [filter-text (some-> filter-text not-empty .toLowerCase)]
   (filter #(-> % 
                .toLowerCase 
                (.indexOf filter-text)
                (not= -1)) 
           alist)
   alist))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top