Welcome! Please see the About page for a little more info on how this works.

0 votes
in Clojure by
closed by

What do you think about adding the index-by function to the core namespace? It's like group-by but doesn't create a vector:

(defn index-by
  "Return a map where a key is (f item) and a value is item."
  {:added "1.11"
   :static true}
  [f coll]
  (persistent!
   (reduce
    (fn [ret x]
      (assoc! ret (f x) x))
    (transient {}) coll)))

I've been using this function for years especially for indexing a database result. Often, you have a vector of maps where each map has a unique ID, and you need to build a map like ID => row. Why don't instroduce such a function? I can create a PR.

by
It occurs to me that this is a special case of `group-by-reduce` ( https://cnuernber.github.io/ham-fisted/ham-fisted.api.html#var-group-by-reduce ), perhaps that's relevant to your interests.
by
The key point is, this function should present in the core module. I don't like the idea of bringing a new dependency when 4-5 lines of code is required.
by
got it! Thanks for the clarification.
...