diff --git a/utils/comparator.go b/utils/comparator.go index 98d6e3d..b5f0f79 100644 --- a/utils/comparator.go +++ b/utils/comparator.go @@ -4,6 +4,8 @@ package utils +import "time" + // Comparator will make type assertion (see IntComparator for example), // which will panic if a or b are not of the asserted type. // @@ -51,6 +53,21 @@ func IntComparator(a, b interface{}) int { } } +// TimeComparator provides a basic comparison on time.Time +func TimeComparator(a, b interface{}) int { + aAsserted := a.(time.Time) + bAsserted := b.(time.Time) + + switch { + case aAsserted.After(bAsserted) : + return 1 + case aAsserted.Before(bAsserted): + return -1 + default: + return 0 + } +} + // Int8Comparator provides a basic comparison on int8 func Int8Comparator(a, b interface{}) int { aAsserted := a.(int8) diff --git a/utils/comparator_test.go b/utils/comparator_test.go index 12849f8..00d028f 100644 --- a/utils/comparator_test.go +++ b/utils/comparator_test.go @@ -6,6 +6,7 @@ package utils import ( "testing" + "time" ) func TestIntComparator(t *testing.T) { @@ -30,6 +31,27 @@ func TestIntComparator(t *testing.T) { } } + +func TestTimeComparator(t *testing.T) { + + now := time.Now() + + // i1,i2,expected + tests := [][]interface{}{ + {now, now, 0}, + {now.Add(24 * 7 * 2 * time.Hour), now, 1}, + {now, now.Add(24 * 7 * 2 * time.Hour), -1}, + } + + for _, test := range tests { + actual := TimeComparator(test[0], test[1]) + expected := test[2] + if actual != expected { + t.Errorf("Got %v expected %v", actual, expected) + } + } +} + func TestStringComparator(t *testing.T) { // s1,s2,expected