Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A 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 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)

like image 981
leontalbot Avatar asked Apr 20 '14 19:04

leontalbot


2 Answers

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.

like image 50
NielsK Avatar answered Oct 25 '22 00:10

NielsK


(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))
like image 27
Leon Grapenthin Avatar answered Oct 25 '22 00:10

Leon Grapenthin