Skip to content

Instantly share code, notes, and snippets.

@athomasoriginal
Last active September 7, 2021 12:59
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 athomasoriginal/c7915d02636515a460d19aa24c457502 to your computer and use it in GitHub Desktop.
Save athomasoriginal/c7915d02636515a460d19aa24c457502 to your computer and use it in GitHub Desktop.
;; Example state
;; -----------------------------------
(def stocks-db
{1 {:id 1 :type :asset :parent-id 2}
2 {:id 2 :type :group :parent-id nil}
3 {:id 3 :type :asset :parent-id 2}})
;; Exammple db state -> tree transform
;; -----------------------------------
(defn stocks->stock-groups
[stocks]
(->> (vals stocks)
(group-by :parent-id)))
(defn stock-tree
[stocks]
(let [group->children (stocks->stock-groups stocks)
tree-nodes (fn tree-nodes [parent-id]
(->> (get group->children parent-id)
(map #(assoc % :nodes (tree-nodes (:id %))))))]
;; `nil` indicates a root node
(tree-nodes nil)))
;; Exammple event handlers
;; -----------------------
(defn edit-node!
[stocks node-id stock]
(swap! stocks assoc node-id stock))
(defn delete-node!
[stocks node-id]
(swap! stocks dissoc node-id))
(defn add-node!
[stocks node-id stock]
(swap! stocks assoc node-id stock))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment