A case-insensitive filter in Clojure / ClojureScript

為{幸葍}努か 提交于 2019-12-07 09:26:37

问题


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)


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/23186490/a-case-insensitive-filter-in-clojure-clojurescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!