replaced github.com/xhit/go-str2duration with my own func + tests

This commit is contained in:
2022-10-16 15:30:34 +02:00
parent dfd3ab9b77
commit da276a1b50
6 changed files with 123 additions and 15 deletions

View File

@@ -19,7 +19,7 @@ package lib
import (
"github.com/araddon/dateparse"
str2duration "github.com/xhit/go-str2duration/v2"
"regexp"
"sort"
"strconv"
)
@@ -63,15 +63,9 @@ func compare(a string, b string) bool {
}
comp = left < right
case "duration":
left, err := str2duration.ParseDuration(a)
if err != nil {
left = 0
}
right, err := str2duration.ParseDuration(b)
if err != nil {
right = 0
}
comp = left.Seconds() < right.Seconds()
left := duration2int(a)
right := duration2int(b)
comp = left < right
case "time":
left, _ := dateparse.ParseAny(a)
right, _ := dateparse.ParseAny(b)
@@ -86,3 +80,37 @@ func compare(a string, b string) bool {
return comp
}
/*
We could use time.ParseDuration(), but this doesn't support days.
We could also use github.com/xhit/go-str2duration/v2, which does
the job, but it's just another dependency, just for this little
gem. And we don't need a time.Time value. And int is good enough
for duration comparision.
Convert a durartion into an integer. Valid time units are "s",
"m", "h" and "d".
*/
func duration2int(duration string) int {
re := regexp.MustCompile(`(\d+)([dhms])`)
seconds := 0
for _, match := range re.FindAllStringSubmatch(duration, -1) {
if len(match) == 3 {
v, _ := strconv.Atoi(match[1])
switch match[2][0] {
case 'd':
seconds += v * 86400
case 'h':
seconds += v * 3600
case 'm':
seconds += v * 60
case 's':
seconds += v
}
}
}
return seconds
}