1 | export default class TokenBucket {
|
2 | private lastTime: number
|
3 | private left: number
|
4 | private capacity: number
|
5 | private refillRate: number
|
6 |
|
7 | constructor ({ refillPeriod, refillCount, capacity }: { refillPeriod: number, refillCount: number, capacity?: number }) {
|
8 | this.lastTime = Date.now()
|
9 | this.capacity = (typeof capacity !== 'undefined') ? capacity : refillCount
|
10 | this.left = this.capacity
|
11 | this.refillRate = refillCount / refillPeriod
|
12 | }
|
13 |
|
14 | take (count: number = 1) {
|
15 | const now = Date.now()
|
16 | const delta = Math.max(now - this.lastTime, 0)
|
17 | const amount = delta * this.refillRate
|
18 |
|
19 | this.lastTime = now
|
20 | this.left = Math.min(this.left + amount, this.capacity)
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 | if (this.left < count) {
|
28 | return false
|
29 | }
|
30 |
|
31 | this.left -= count
|
32 | return true
|
33 | }
|
34 | }
|