multi-key-stable-sort-with-nils
Clojure
(defn sort-records
"Stable multi-key sort; specs are [:age :asc]. nil compares lower than any other value."
[rows & specs]
(sort (fn [a b]
(or (some (fn [[k dir]]
(let [c (compare (get a k) (get b k))]
(when-not (zero? c)
(if (= :desc dir) (- c) c))))
specs)
0))
rows))
;; (sort-records [{:age 2} {:age nil}] [:age :asc])