Fork me on GitHub
#datomic
<
2017-11-21
>
timgilbert18:11:22

Say, anybody got a "recursively touch entity e to depth n" function lying around? I saw this but I need to handle the {:db/valueType :db.type/ref :db/cardinality :db.cardinality/many} case. https://stackoverflow.com/questions/27072840/how-to-write-touch-all-touch-all-reachable-entities-from-an-entity-in-datomic

timgilbert18:11:07

Well, this is what I came up with, not the prettiest or most efficient, but it works well enough for debugging purposes.

(defn touch-n
  "Recursively touch an entity to n levels deep (default 2). Return a nested map."
  ([e]
   (touch-n 2 e))
  ([n e]
   (if (or (zero? n) (not (entity? e)))
     ;; We've reached our recursion limit, or we're at a leaf node
     e
     ;; Else we're an an entity, touch it an recur
     (reduce (fn [m [k v]]
               (assoc m k (if (set? v)
                            ;; Cardinality many
                            (into #{} (map (partial touch-n (dec n)) v))
                            ;; Cardinality one
                            (touch-n (dec n) v))))
             {}
             (d/touch e)))))

timgilbert18:11:36

(where I've already got (defn entity? [thing] (instance? datomic.Entity thing)))