Case Insensitive Filter in Clojure / ClojureScript

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 respecting the fact that I don’t want a case-sensitive filter, that is, I would like (list-data ["Lion" "Zebra" "Buffalo" "Antelope"] "a") returned the following:

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

Thanks!

(This should work in a .cljs file)

+4
clojure clojurescript
source share
2 answers

In Clojure, you usually do this with a regex. In Java regular expressions, you can do this by specifying a checkbox for case insensitivity for the match you want to do, or at the beginning of a regular expression for global case insensitivity:

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

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

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

However, since the convenience and preservation of regular expressions between Java and Javascript is similar, the Clojurescript reader translates Java-style global flags (those at the beginning of the regular expression) into their global Javascript equivalent.

So, the first example also works in Clojurescript. Keep in mind that non-global flags will not work in Clojurescript, where they will work in Clojure.

+13
source share
 (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)) 
+4
source share

All Articles