Repository navigation
Expand file tree
/
Copy pathrollingWindowSlice.go
More file actions
79 lines (66 loc) · 1.88 KB
/
Copy pathrollingWindowSlice.go
File metadata and controls
79 lines (66 loc) · 1.88 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"errors"
"time"
)
// RollingWindowSlice is a slice implementation of RollowingWindow
type RollingWindowSlice struct {
window *[]time.Time
size int
currentIndex int
}
// NewRollingWindowSlice bla
func NewRollingWindowSlice(size int) *RollingWindowSlice {
w := &[]time.Time{}
return &RollingWindowSlice{
window: w,
size: size,
currentIndex: 0,
}
}
func (rws *RollingWindowSlice) get() time.Time {
return (*rws.window)[rws.currentIndex]
}
func (rws *RollingWindowSlice) hasNext() bool {
// fmt.Println("len", len(*rws.window), "current ", rws.currentIndex)
nextIndex := rws.currentIndex + 1
return len(*rws.window) > nextIndex
}
func (rws *RollingWindowSlice) next() (time.Time, error) {
if rws.hasNext() {
rws.currentIndex++
return (*rws.window)[rws.currentIndex], nil
}
return time.Time{}, errors.New("No next element")
}
func (rws *RollingWindowSlice) remove() {
*rws.window = append((*rws.window)[:rws.currentIndex], (*rws.window)[rws.currentIndex+1:]...)
}
func (rws *RollingWindowSlice) windowSize() int {
return rws.size
}
func (rws *RollingWindowSlice) GetCount() int {
return len(*rws.window)
}
func (rws *RollingWindowSlice) AppendRequest(timestamp time.Time) {
*rws.window = append(*rws.window, timestamp)
}
func computeWindowBoundary(now time.Time, size int) time.Time {
windowSize := -time.Duration(size)
return now.Add(windowSize * time.Second)
}
func (rws *RollingWindowSlice) garbageCollect(rw RollingWindowDataStructure) {
for rws.hasNext() {
rws.next()
now := time.Now()
wb := computeWindowBoundary(now, rws.windowSize())
for currTimestamp := rws.get(); rws.hasNext(); currTimestamp, _ = rws.next() {
if !isTimeStampWithinWindow(wb, currTimestamp) {
rws.remove()
}
}
}
}
// func addRequestToWindow(rw RollingWindowDataStructure, timestamp time.Time) {
// rw.AppendRequest(timestamp)
// }