Skip to content

Instantly share code, notes, and snippets.

@ertugrulcetin
Last active June 14, 2022 11:39
Show Gist options
  • Save ertugrulcetin/27c1f37575051a6f65d106d430caa4b1 to your computer and use it in GitHub Desktop.
Save ertugrulcetin/27c1f37575051a6f65d106d430caa4b1 to your computer and use it in GitHub Desktop.
Clojure: sort by multiple keys with different orderings
;; https://www.reddit.com/r/Clojure/comments/ufa8e0/clojure_sort_by_multiple_keys_with_different/
(let [sort-fns-map {:asc (fn [a b] (. clojure.lang.Util compare a b))
:desc (fn [a b] (. clojure.lang.Util compare b a))}]
(defn by [& keys-orderings]
(fn [a b]
(loop [[key ordering & keys-orderings] keys-orderings]
(let [order ((get sort-fns-map ordering ordering) (key a) (key b))]
(if (and (zero? order) keys-orderings)
(recur keys-orderings)
order))))))
(sort (by :birthyear :desc :surname :asc) [{:birthyear 1990 :surname "ertu"}
{:birthyear 1992 :surname "ertu"}])
(sort (by :birthyear :desc :surname (fn [a b] (. clojure.lang.Util compare b a)))
[{:birthyear 1990 :surname "ertu"}
{:birthyear 1992 :surname "ertu"}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment