【rich function】VersionCompare replace

master
sunwei 4 years ago committed by Kevin Wan
parent 945d59a980
commit e18ca9aac1

@ -5,37 +5,6 @@ import (
"strings" "strings"
) )
// returns -1 if the first version is lower than the second, 0 if they are equal, and 1 if the second is lower.
func CompareVersions(a, b string) int {
as := strings.Split(a, ".")
bs := strings.Split(b, ".")
var loop int
if len(as) > len(bs) {
loop = len(as)
} else {
loop = len(bs)
}
for i := 0; i < loop; i++ {
var x, y string
if len(as) > i {
x = as[i]
}
if len(bs) > i {
y = bs[i]
}
xi, _ := strconv.Atoi(x)
yi, _ := strconv.Atoi(y)
if xi > yi {
return 1
} else if xi < yi {
return -1
}
}
return 0
}
//return 0 if they are equal,and 1 if v1>2,and 2 if v1<v2 //return 0 if they are equal,and 1 if v1>2,and 2 if v1<v2
func Compare(v1, v2 string) int { func Compare(v1, v2 string) int {
replaceMap := map[string]string{"V": "", "v": "", "-": "."} replaceMap := map[string]string{"V": "", "v": "", "-": "."}
@ -95,8 +64,8 @@ func strSlice2IntSlice(strs []string) []int64 {
return retInt return retInt
} }
//custom operator compare //operator compare returns true if the first field and the second field are equal else false
func CustomCompareVersions(v1, v2, operator string) bool { func CompareVersions(v1, v2, operator string) bool {
com := Compare(v1, v2) com := Compare(v1, v2)
switch operator { switch operator {
case "==": case "==":

@ -6,29 +6,6 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestCompareVersions(t *testing.T) {
cases := []struct {
ver1 string
ver2 string
out int
}{
{"1", "1.0.1", -1},
{"1.0.1", "1.0.2", -1},
{"1.0.3", "1.1", -1},
{"1.1", "1.1.1", -1},
{"1.3.2", "1.2", 1},
{"1.1.1", "1.1.1", 0},
{"1.1.0", "1.1", 0},
}
for _, each := range cases {
t.Run(each.ver1, func(t *testing.T) {
actual := CompareVersions(each.ver1, each.ver2)
assert.Equal(t, each.out, actual)
})
}
}
func TestCustomCompareVersions(t *testing.T) { func TestCustomCompareVersions(t *testing.T) {
cases := []struct { cases := []struct {
ver1 string ver1 string
@ -53,7 +30,7 @@ func TestCustomCompareVersions(t *testing.T) {
for _, each := range cases { for _, each := range cases {
t.Run(each.ver1, func(t *testing.T) { t.Run(each.ver1, func(t *testing.T) {
actual := CustomCompareVersions(each.ver1, each.ver2, each.operator) actual := CompareVersions(each.ver1, each.ver2, each.operator)
assert.Equal(t, each.out, actual) assert.Equal(t, each.out, actual)
}) })
} }

Loading…
Cancel
Save