mirror of
https://github.com/blindlobstar/go-interview-problems
synced 2025-04-28 04:35:14 +00:00
26 lines
382 B
Go
26 lines
382 B
Go
package solution
|
|
|
|
import "time"
|
|
|
|
type RateLimiter struct {
|
|
ticker *time.Ticker
|
|
}
|
|
|
|
func NewRateLimiter(n int) *RateLimiter {
|
|
limit := time.Second / time.Duration(n)
|
|
return &RateLimiter{ticker: time.NewTicker(limit)}
|
|
}
|
|
|
|
func (r *RateLimiter) CanTake() bool {
|
|
select {
|
|
case <-r.ticker.C:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func (r *RateLimiter) Take() {
|
|
<-r.ticker.C
|
|
}
|