Last active
December 16, 2015 22:39
-
-
Save martintrojer/5508704 to your computer and use it in GitHub Desktop.
filter-map-entries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; filter keys and values in json-like nested maps and vectors | |
(defn filter-map-entries [pred m] | |
(loop [acc {}, [[k v] & tail] (if (map? m) (seq m) (map seq m))] | |
(if k | |
(cond (pred [k k]) (recur (conj acc [k v]) tail) | |
(map? v) (let [submap (filter-map-entries pred v)] | |
(if (empty? submap) | |
(recur acc tail) | |
(recur (conj acc [k submap]) tail))) | |
(vector? v) (let [ms (->> v (map #(if (coll? %) | |
(filter-map-entries pred %) | |
(if (pred [% %]) [%] []))) | |
(remove empty?) | |
vec)] | |
(if (empty? ms) | |
(recur acc tail) | |
(recur (conj acc [k ms]) tail))) | |
:else (if (pred [k v]) (recur (conj acc [k v]) tail) (recur acc tail))) | |
acc))) | |
(defn mapentry-matches? [pat [k v]] | |
(or (core/re? pat (-> k str string/lower-case)) | |
(core/re? pat (-> v str string/lower-case)))) | |
(defn fme [pat-str m] | |
(let [pat (-> pat-str string/lower-case java.util.regex.Pattern/compile)] | |
(filter-map-entries (partial mapentry-matches? pat) m))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; yeah... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment