Last active
August 20, 2017 09:09
-
-
Save ertugrulcetin/8a4d391c8414beb983905e1849828a02 to your computer and use it in GitHub Desktop.
Finding indexes in nested data structure
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
(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