Last active
September 7, 2021 12:59
-
-
Save athomasoriginal/c7915d02636515a460d19aa24c457502 to your computer and use it in GitHub Desktop.
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
;; 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