From 920bd075c562c1ed8361d344df5068e322edb2ca Mon Sep 17 00:00:00 2001 From: Peter Taoussanis Date: Mon, 23 Sep 2024 13:02:40 +0200 Subject: [PATCH] [new] Add `invert-map!` --- src/taoensso/encore.cljc | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/taoensso/encore.cljc b/src/taoensso/encore.cljc index 03f7201e..0ca37e6d 100644 --- a/src/taoensso/encore.cljc +++ b/src/taoensso/encore.cljc @@ -2509,6 +2509,17 @@ (persistent! (reduce-kv (fn [m k v] (assoc! m v k)) (transient {}) m)) (do (reduce-kv (fn [m k v] (assoc m v k)) {} m))))) +(defn invert-map! + "Like `invert-map` but throws on non-unique vals." + {:added "Encore vX.Y.Z (YYYY-MM-DD)"} + [m] + (when-let [im (invert-map m)] + (if (= (count im) (count m)) ; 1-to-1 + im + (throw + (ex-info "[encore/invert-map!] Non-unique map vals" + {:given (typed-val m)}))))) + (defn map-keys "Returns given ?map with (key-fn ) keys." [key-fn m]