From 6d1a6fbfa41bcf34f8b94cec60f9009a2a7b8032 Mon Sep 17 00:00:00 2001 From: Andy Fingerhut Date: Mon, 1 Apr 2013 19:04:05 -0700 Subject: [PATCH] Fix a couple of bugs in key-comparator and add two tests that fail without the fixes. --- src/flatland/useful/fn.clj | 4 ++-- test/flatland/useful/fn_test.clj | 11 +++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/flatland/useful/fn.clj b/src/flatland/useful/fn.clj index 269898f..9bb98d0 100644 --- a/src/flatland/useful/fn.clj +++ b/src/flatland/useful/fn.clj @@ -132,9 +132,9 @@ (transform y)." ([modifier] (fn [a b] - (- (modifier a) (modifier b)))) + (compare (modifier a) (modifier b)))) ([direction modifier] - (let [f (comparator modifier)] + (let [f (key-comparator modifier)] (condp #(% %2) direction #{:desc :descending -} (comp - f) #{:asc :ascending +} f)))) diff --git a/test/flatland/useful/fn_test.clj b/test/flatland/useful/fn_test.clj index c08e2f6..2bfe03a 100644 --- a/test/flatland/useful/fn_test.clj +++ b/test/flatland/useful/fn_test.clj @@ -79,3 +79,14 @@ (deftest test-ignoring-nils (is (= 6 ((ignoring-nils +) 1 nil 2 nil nil 3)))) + +(deftest test-key-comparator + (let [subtract-comparator-fn-breaks-on-this [2147483650 2147483651 + 2147483652 4 2 3 1] + normal-cmp (key-comparator identity)] + (is (= (sort subtract-comparator-fn-breaks-on-this) + (sort normal-cmp subtract-comparator-fn-breaks-on-this)))) + (let [square (fn [x] (* x x)) + by-square (key-comparator :ascending square)] + (is (= (sort-by square [-9 -5 1 -2]) + (sort by-square [-9 -5 1 -2])))))