/
version.go
41 lines (38 loc) · 1.2 KB
/
version.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package ainur
import (
"math"
"strconv"
"strings"
)
// versionSum takes a slice of strings that are the parts of a version number.
// The parts are converted to numbers. If they can't be converted, they count
// as less than nothing. The parts are then summed together, but with more
// emphasis put on the earlier numbers. 2.0.0.0 has emphasis 2000.
// The sum is then returned.
func versionSum(parts []string) int {
sum := 0
length := len(parts)
for i := length - 1; i >= 0; i-- {
num, err := strconv.Atoi(parts[i])
if err != nil {
num = -1
}
sum += num * int(math.Pow(float64(10), float64(length-i-1)))
}
return sum
}
// FirstIsGreater checks if the first version number is greater than the second one.
// It uses a relatively simple algorithm, where all non-numbers counts as less than "0".
func FirstIsGreater(a, b string) bool {
aParts := strings.Split(a, ".")
bParts := strings.Split(b, ".")
// Expand the shortest version list with zeroes
for len(aParts) < len(bParts) {
aParts = append(aParts, "0")
}
for len(bParts) < len(aParts) {
bParts = append(bParts, "0")
}
// The two lists that are being compared should be of the same length
return versionSum(aParts) > versionSum(bParts)
}