mirror of
https://codeberg.org/scip/tablizer.git
synced 2025-12-17 12:31:06 +01:00
replaced github.com/xhit/go-str2duration with my own func + tests
This commit is contained in:
48
lib/sort.go
48
lib/sort.go
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user