Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ;; "results" has been pulled out of a database via sql query.
- ;; It's already in the correct order, and even has depth information (not that I'm using it).
- ;; The threadify function turns the vector of SQL results into a thread that looks like __dummy_thread__ below.
- ;; The SQL results have all the same keys/vals as you see in the dummy thread, with the additional key :parent
- ;; (which refers to the parent ID for a given post).
- (defn threadify
- ([results]
- (let [children (fn [node] (:children node))
- make-node (fn [node children-seq] (assoc node :children (vec children-seq)))]
- (threadify results
- (zip/zipper (constantly true) children make-node {})
- 0)))
- ([results tree total]
- (if (empty? results)
- (into [total] (:children (zip/root tree)))
- (let [[hd & tl] results
- parent (:parent hd)
- parent-node (loop [current-pos tree
- last-pos tree]
- (cond (nil? current-pos) last-pos
- (= parent (:id (zip/node current-pos))) current-pos
- :else (recur (zip/up current-pos) current-pos)))]
- (recur tl
- (-> parent-node
- (zip/append-child hd)
- zip/down
- zip/rightmost)
- (inc total))))))
- (def __dummy_thread__
- ["boardname"
- 2
- {:author "Poster1"
- :subject "First post!"
- :time 1431811264
- :id 1
- :children [{:author "Poster2"
- :subject "Me too!"
- :time 1431811307
- :id 2
- :children [{:author "Poster1"
- :subject "Me too posts are discouraged."
- :body "You heathen."
- :time 1431811360
- :id 55}]}]}])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement