Skip to content

Instantly share code, notes, and snippets.

@martintrojer
Last active December 16, 2015 22:39
Show Gist options
  • Save martintrojer/5508704 to your computer and use it in GitHub Desktop.
Save martintrojer/5508704 to your computer and use it in GitHub Desktop.
filter-map-entries
;; 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)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment