Skip to content

Instantly share code, notes, and snippets.

@ertugrulcetin
Last active August 20, 2017 09:09
Show Gist options
  • Save ertugrulcetin/8a4d391c8414beb983905e1849828a02 to your computer and use it in GitHub Desktop.
Save ertugrulcetin/8a4d391c8414beb983905e1849828a02 to your computer and use it in GitHub Desktop.
Finding indexes in nested data structure
(defn find-index-route
[x form]
(letfn [(get-nodes [form]
(tree-seq coll? identity form))
(get-tree [form]
(rest (get-nodes form)))
(get-level [form]
(if (or (not (coll? form)) (not (seq form)))
0
(count (filter coll? (get-nodes form)))))
(get-result [x form]
(reduce (fn [v form]
(let [[idx lvl _] (last v)
form-lvl (get-level form)
contains? ((set (get-nodes form)) x)]
(conj v [(if (or (not idx) (< form-lvl lvl)) 0 (+ idx 1))
form-lvl
contains?]))) [] (get-tree form)))
(get-indices [x form]
(map (fn [[idx _ _]] idx)
(filter
(fn [[_ _ contains?]] contains?) (get-result x form))))]
(get-indices x form)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment