Skip to content

Instantly share code, notes, and snippets.

@martinklepsch
Last active August 29, 2015 14:17
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 martinklepsch/4902c514c235dfa85f84 to your computer and use it in GitHub Desktop.
Save martinklepsch/4902c514c235dfa85f84 to your computer and use it in GitHub Desktop.
(def input
[{:t "A" :id 1}
{:t "B" :id 2 :parent 1}
{:t "C" :id 3 :parent 2}
{:t "D" :id 4 :parent 1}
{:t "E" :id 5 :parent 1}
{:t "F" :id 6 :parent 5}
{:t "G" :id 7 :parent 6}
{:t "H" :id 8 :parent 1}])
;; desired output
(def desired-output
{:t "A" :id 1
:children [{:t "B" :id 2 :parent 1
:children [{:t "C" :id 3 :parent 2}]}
{:t "D" :id 4 :parent 1}
{:t "E" :id 5 :parent 1
:children [{:t "F" :id 6 :parent 5
:children [{:t "G" :id 7 :parent 6}]}]}
{:t "H" :id 8 :parent 1}]})
;; potential solution:
(defn gather-children [m msgs]
(assoc m :children (map #(gather-children % msgs)
(filter #(= (:id m) (:parent %)) msgs))))
(pprint
(gather-children (first input) input))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment