gods/utils/comparator.go

53 lines
1.1 KiB
Go
Raw Normal View History

// 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-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.
//
// 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 {
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)
}
if diff < 0 {
return -1
}
if diff > 0 {
return 1
}
return 0
2015-03-04 17:55:52 +00:00
}