I wanted to sort a sequence of maps using a spec consisting of an ordered map of key and order, like this:
(array-map :name 1 :age -1)
I couldn't find a ready-made solution, so I rolled my own. I ended up with three functions with a total of 10 lines of code. Two of them are generic, and one is specific to my problem.
First a comparator-generator, that is fed a collection of comparators:
(defn compare-many [comps]
(fn [xs ys]
(if-let [result (first (drop-while zero? (map (fn [f x y] (. f (compare x y))) comps xs ys)))]
result
0)))
It uses the same trick as sort-by does, namely the fact that all functions implement Comparator. This means that I can pass in a predicate instead of a comparator, if it makes sense:
user=> ((compare-many [> compare]) [4 "beta"] [4 "alpha"])
1
user=> ((compare-many [> compare]) [4 "beta"] [3 "gamma"])
-1
Next, a convenience function that takes a collection of keyfns, a collection of comparators (or predicates), and a collection to sort, passing it to
sort-by:
(defn sort-by-many [keyfns comps coll] (sort-by (apply juxt keyfns) (compare-many comps) coll))
It's called like this:
user=> (sort-by-many [:a :b] [> compare] [{:a 4 :b "beta"} {:a 4 :b "alpha"} {:a 3 :b "gamma"} {:a 5 :b "delta"}])
({:a 5, :b "delta"}
{:a 4, :b "alpha"}
{:a 4, :b "beta"}
{:a 3, :b "gamma"})
And finally a function specific to my problem domain. It takes a sort order map and the collection to sort (note that I use (comp - compare) to get the inverse sort order):
(defn sort-by-map [m coll]
(sort-by-many (keys m)
(map #(case % 1 compare -1 (comp - compare) (throw (Exception. "1 or -1"))) (vals m))
coll))
It's called like this:
user=> (sort-by-map (array-map :name 1 :age -1)
[{:name "zack" :age 25} {:name "amanda" :age 19} {:name "zack" :age 20} {:name "zack" :age 21}])
({:age 19, :name "amanda"}
{:age 25, :name "zack"}
{:age 21, :name "zack"}
{:age 20, :name "zack"})
The collection doesn't have to contain maps:
user=> (sort-by-map (array-map first 1 second -1) [["zack" 25] ["amanda" 19] ["zack" 20] ["zack" 21]])
(["amanda" 19]
["zack" 25]
["zack" 21]
["zack" 20])
Is there anything that I've missed? Improvements?