2016-06-27 02:21:09 +00:00
|
|
|
// Copyright (c) 2015, Emir Pasic. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
2015-03-06 16:10:34 +00:00
|
|
|
|
2015-03-04 17:55:52 +00:00
|
|
|
package utils
|
|
|
|
|
|
|
|
// Comparator will make type assertion (see IntComparator for example),
|
|
|
|
// which will panic if a or b are not of the asserted type.
|
|
|
|
//
|
2016-06-25 15:02:21 +00:00
|
|
|
// Should return a number:
|
|
|
|
// negative , if a < b
|
|
|
|
// zero , if a == b
|
|
|
|
// positive , if a > b
|
2015-03-04 17:55:52 +00:00
|
|
|
type Comparator func(a, b interface{}) int
|
|
|
|
|
2016-06-24 19:52:16 +00:00
|
|
|
// IntComparator provides a basic comparison on ints
|
2015-03-04 17:55:52 +00:00
|
|
|
func IntComparator(a, b interface{}) int {
|
2016-09-07 03:07:13 +00:00
|
|
|
aInt := a.(int)
|
|
|
|
bInt := b.(int)
|
|
|
|
switch {
|
|
|
|
case aInt > bInt:
|
|
|
|
return 1
|
|
|
|
case aInt < bInt:
|
|
|
|
return -1
|
|
|
|
default:
|
|
|
|
return 0
|
|
|
|
}
|
2015-03-04 17:55:52 +00:00
|
|
|
}
|
|
|
|
|
2016-06-24 19:52:16 +00:00
|
|
|
// StringComparator provides a fast comparison on strings
|
2015-03-04 17:55:52 +00:00
|
|
|
func StringComparator(a, b interface{}) int {
|
|
|
|
s1 := a.(string)
|
|
|
|
s2 := b.(string)
|
|
|
|
min := len(s2)
|
|
|
|
if len(s1) < len(s2) {
|
|
|
|
min = len(s1)
|
|
|
|
}
|
|
|
|
diff := 0
|
|
|
|
for i := 0; i < min && diff == 0; i++ {
|
|
|
|
diff = int(s1[i]) - int(s2[i])
|
|
|
|
}
|
|
|
|
if diff == 0 {
|
|
|
|
diff = len(s1) - len(s2)
|
|
|
|
}
|
2015-03-06 00:35:03 +00:00
|
|
|
if diff < 0 {
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
if diff > 0 {
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
return 0
|
2015-03-04 17:55:52 +00:00
|
|
|
}
|