mirror of
https://github.com/emirpasic/gods
synced 2024-11-08 13:10:26 +00:00
53 lines
1.1 KiB
Go
53 lines
1.1 KiB
Go
// 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.
|
|
|
|
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
|
|
type Comparator func(a, b interface{}) int
|
|
|
|
// IntComparator provides a basic comparison on ints
|
|
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
|
|
}
|
|
}
|
|
|
|
// StringComparator provides a fast comparison on strings
|
|
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
|
|
}
|