Skip to content

Instantly share code, notes, and snippets.

@cndreisbach
Created July 1, 2013 20:49
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 cndreisbach/5904510 to your computer and use it in GitHub Desktop.
Save cndreisbach/5904510 to your computer and use it in GitHub Desktop.
(ns monger.key-compression)
(def select (comp first filter))
(defn- trie-add
[trie words]
(reduce
(fn [trie word]
(assoc-in trie (concat word [::val]) word))
trie
words))
(defn- trie-matches
[trie prefix]
(letfn [(search [node]
(mapcat (fn [[k v]]
(if (= ::val k) [v] (search v)))
node))]
(search (get-in trie prefix))))
(defn- get-prefixes
[field]
(reduce
(fn [prefixes letter]
(conj prefixes ((fnil str "") (last prefixes) letter)))
[]
field))
(defn- get-unique-prefix
[field trie]
(let [prefixes (get-prefixes field)]
(select (fn [prefix] (or (= 1 (count (trie-matches trie prefix)))
(= prefix field)))
prefixes)))
(defn create-compression-map
"Create a map of shortened unique field names from a list of fields."
[field-list]
(let [field-list (map name field-list)
field-trie (trie-add {} field-list)]
(into {}
(map
(fn [field]
[(keyword (get-unique-prefix field field-trie)) field])
field-list))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment