Last active
June 14, 2022 11:39
-
-
Save ertugrulcetin/27c1f37575051a6f65d106d430caa4b1 to your computer and use it in GitHub Desktop.
Clojure: sort by multiple keys with different orderings
This file contains 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
;; 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