Skip to content

Commit fa384f5

Browse files
committed
Implement sliding window
1 parent 1231032 commit fa384f5

File tree

1 file changed

+46
-1
lines changed

1 file changed

+46
-1
lines changed
Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,46 @@
1-
// internal/algorithm/sliding_window.go
1+
package algorithm
2+
3+
import (
4+
"sync"
5+
"time"
6+
)
7+
8+
type SlidingWindow struct {
9+
mu sync.Mutex
10+
requests []time.Time
11+
limit int
12+
window time.Duration
13+
}
14+
15+
func NewSlidingWindoe(limit int, window time.Duration) *SlidingWindow {
16+
return &SlidingWindow{limit: limit, window: window}
17+
}
18+
19+
func (sw: *SlidingWindow) Allow() bool {
20+
sw.mu.Lock()
21+
defer sw.mu.Unlock()
22+
23+
now := time.Now()
24+
cutoff := now.Add(-sw.window)
25+
26+
valid := sw.requests[:0]
27+
for _, t := range sw.requests {
28+
if t.After(cutoff) {
29+
valid = append(valid, t)
30+
}
31+
}
32+
sw.requests = valid
33+
34+
if len(sw.requests) >= sw.limit {
35+
return false
36+
}
37+
38+
sw.requests = append(sw.requests, now)
39+
return true
40+
}
41+
42+
func (sw *SlidingWindow) Count() int {
43+
sw.mu.Lock()
44+
defer sw.mu.Unlock()
45+
return len(sw.requests)
46+
}

0 commit comments

Comments
 (0)