From bc011bbf43d865d2003ebed26eaf512c7ef2224e Mon Sep 17 00:00:00 2001 From: Nick Alexander Date: Tue, 4 Oct 2016 11:34:28 -0700 Subject: [PATCH] Pre: Add util/group-by-kv. --- src/common/datomish/util.cljc | 14 ++++++++++++++ test/datomish/util_test.cljc | 5 +++++ 2 files changed, 19 insertions(+) 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]]))