Skip to content

Instantly share code, notes, and snippets.

@favila
Created November 11, 2015 21:12
Show Gist options
  • Save favila/154f08d280110bce8643 to your computer and use it in GitHub Desktop.
Save favila/154f08d280110bce8643 to your computer and use it in GitHub Desktop.
Efficient clojure(script) unique? function, optionally taking a key function.
(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