Created
November 11, 2015 21:12
-
-
Save favila/154f08d280110bce8643 to your computer and use it in GitHub Desktop.
Efficient clojure(script) unique? function, optionally taking a key function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn unique? | |
"Return true if a collection's items are unique, else false | |
With a key function, will return true if `(map keyfn coll)` is unique, else false." | |
([coll] (unique? coll identity)) | |
([coll keyfn] | |
(or (set? coll) (map? coll) | |
(some? (reduce | |
(fn [seen x] | |
(let [k (keyfn x)] | |
(if (contains? seen k) | |
(reduced nil) | |
(conj seen k)))) | |
#{} coll))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment