Advertisement
Guest User

Untitled

a guest
Aug 2nd, 2017
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ;; "results" has been pulled out of a database via sql query.
  2. ;; It's already in the correct order, and even has depth information (not that I'm using it).
  3. ;; The threadify function turns the vector of SQL results into a thread that looks like __dummy_thread__ below.
  4. ;; The SQL results have all the same keys/vals as you see in the dummy thread, with the additional key :parent
  5. ;; (which refers to the parent ID for a given post).
  6.  
  7. (defn threadify
  8.   ([results]
  9.    (let [children (fn [node] (:children node))
  10.          make-node (fn [node children-seq] (assoc node :children (vec children-seq)))]
  11.      (threadify results
  12.                 (zip/zipper (constantly true) children make-node {})
  13.                 0)))
  14.   ([results tree total]
  15.    (if (empty? results)
  16.      (into [total] (:children (zip/root tree)))
  17.      (let [[hd & tl] results
  18.            parent (:parent hd)
  19.            parent-node (loop [current-pos tree
  20.                               last-pos tree]
  21.                          (cond (nil? current-pos) last-pos
  22.                                (= parent (:id (zip/node current-pos))) current-pos
  23.                                :else (recur (zip/up current-pos) current-pos)))]
  24.        (recur tl
  25.               (-> parent-node
  26.                   (zip/append-child hd)
  27.                   zip/down
  28.                   zip/rightmost)
  29.               (inc total))))))
  30.  
  31. (def __dummy_thread__
  32.   ["boardname"
  33.    2
  34.    {:author   "Poster1"
  35.     :subject  "First post!"
  36.     :time     1431811264
  37.     :id 1
  38.     :children [{:author   "Poster2"
  39.                 :subject  "Me too!"
  40.                 :time     1431811307
  41.                 :id 2
  42.                 :children [{:author  "Poster1"
  43.                             :subject "Me too posts are discouraged."
  44.                             :body    "You heathen."
  45.                             :time    1431811360
  46.                             :id 55}]}]}])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement