diff --git a/src/common/datomish/util.cljc b/src/common/datomish/util.cljc index 13a9ee09..dde3955b 100644 --- a/src/common/datomish/util.cljc +++ b/src/common/datomish/util.cljc @@ -154,3 +154,17 @@ (defn unlimited-buffer [] (UnlimitedBuffer. #?(:cljs (array) :clj (java.util.LinkedList.)))) + +(defn group-by-kv + "Returns a map of the elements of coll keyed by the first element of + the result of f on each element. The value at each key will be a + vector of the second element of the result of f on the corresponding + elements, in the order they appeared in coll." + {:static true} + [f coll] + (persistent! + (reduce + (fn [ret x] + (let [[k v] (f x)] + (assoc! ret k (conj (get ret k []) v)))) + (transient {}) coll))) diff --git a/test/datomish/util_test.cljc b/test/datomish/util_test.cljc index 87f25ce1..f1e215b2 100644 --- a/test/datomish/util_test.cljc +++ b/test/datomish/util_test.cljc @@ -46,3 +46,8 @@ (is (util/unblocking-chan? (a/chan (a/sliding-buffer 10)))) (is (util/unblocking-chan? (a/chan (util/unlimited-buffer)))) (is (not (util/unblocking-chan? (a/chan (a/buffer 10)))))) + +(deftest test-group-by-kvs + (are [m xs] (= m (util/group-by-kv identity xs)) + {:a [1 2] :b [3]} + [[:a 1] [:a 2] [:b 3]]))