Add optimized version of index-by.

This commit is contained in:
Andrey Antukh 2015-12-28 13:31:12 +02:00
parent adbc0c7edd
commit 16eb27b342

View file

@ -6,47 +6,13 @@
;; Data structure manipulation ;; Data structure manipulation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; NOTE: commented because tansients are buggy in cljs?
;; (defn index-by
;; "Return a indexed map of the collection
;; keyed by the result of executing the getter
;; over each element of the collection."
;; [coll getter]
;; (let [data (transient {})]
;; (run! #(do
;; (println (getter %))
;; (assoc! data (getter %) %)) coll)
;; (println "test1:" (keys data))
;; (let [r (persistent! data)]
;; (println "test2:" (keys r))
;; r)))
;; (defn index-by
;; "Return a indexed map of the collection
;; keyed by the result of executing the getter
;; over each element of the collection."
;; [coll getter]
;; (let [data (transient {})]
;; (loop [coll coll]
;; (let [item (first coll)]
;; (if item
;; (do
;; (assoc! data (getter item) item)
;; (recur (rest coll)))
;; (let [_ 1 #_(println "test1:" (keys data))
;; r (persistent! data)]
;; (println "test2:" (keys r))
;; r))))))
(defn index-by (defn index-by
"Return a indexed map of the collection "Return a indexed map of the collection
keyed by the result of executing the getter keyed by the result of executing the getter
over each element of the collection." over each element of the collection."
[coll getter] [coll getter]
(reduce (fn [acc item] (persistent!
(assoc acc (getter item) item)) (reduce #(assoc! %1 (getter %2) %2) (transient {}) coll)))
{}
coll))
(def ^:static index-by-id #(index-by % :id)) (def ^:static index-by-id #(index-by % :id))