Skip to content

Instantly share code, notes, and snippets.

@geraldodev
Created March 24, 2016 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geraldodev/53af13904e6bdf739705 to your computer and use it in GitHub Desktop.
Save geraldodev/53af13904e6bdf739705 to your computer and use it in GitHub Desktop.
(defn filter-options
[{:keys [options filter-fn value-key] :as props} filter-value exclude-options]
{:pre [(ifn? value-key)
(or (vector? exclude-options) (nil? exclude-options))]}
(let [exclude-options (if (vector? exclude-options)
(set exclude-options)
#{})]
(cond
(empty? filter-value)
options
(ifn? filter-fn)
(filter-fn options filter-value exclude-options)
:else
(let [{:keys [ignore-accents ignore-case match-prop match-pos label-key value-key]} props
_ (assert (ifn? label-key))
filter-value (cond-> filter-value
ignore-accents (str/strip-accents)
ignore-case (str/lower-case))
extract-key-fn (case match-prop
:label #(str (label-key %))
:value #(str (value-key %)))
extract-key-fn (cond->> extract-key-fn
(and ignore-accents ignore-case)
(comp str/lower-case str/strip-accents)
ignore-case
(comp str/lower-case)
ignore-accents
(comp str/strip-accents))
match-fn (case match-pos
:start str/starts-with?
:any str/contains?)]
(->> options
(filterv #(and (not (exclude-options (value-key %)))
(match-fn (extract-key-fn %) filter-value))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment