-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeseq.go
57 lines (50 loc) · 1.21 KB
/
timeseq.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package timeseq
import (
"sort"
"time"
)
// Interface is a type which can be sorted according to time
type Interface interface {
// return length
Len() int
// swap items
Swap(i, j int)
// return time of item i
Time(i int) time.Time
// return Slice[i:j]
Slice(i, j int) Interface
}
type sortable struct {
Interface
}
// Less implements sort.Interface.Less()
func (s sortable) Less(i, j int) bool {
return s.Time(i).Before(s.Time(j))
}
// Sort will sort slice by time
func Sort(slice Interface) {
sort.Stable(sortable{Interface: slice})
}
// IsSorted reports whether data is sorted.
func IsSorted(slice Interface) bool {
return sort.IsSorted(sortable{Interface: slice})
}
// Range return a sub slice of given sorted slice according to the interval
func Range(slice Interface, interval Interval) Interface {
i := 0
if interval.NotBefore != nil {
i = sort.Search(slice.Len(), func(i int) bool {
return !slice.Time(i).Before(*interval.NotBefore)
})
}
j := slice.Len()
if interval.NotAfter != nil {
j = sort.Search(slice.Len(), func(j int) bool {
return !slice.Time(j).Before(*interval.NotAfter)
})
if j < slice.Len() && slice.Time(j).Equal(*interval.NotAfter) {
j++
}
}
return slice.Slice(i, j)
}