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
export class TokenBucket {
private bucketSize: number;
private tokens: number;
private refillRate: number;
private lastRefill: number;
constructor(bucketSize: number, refillRate: number) {
this.bucketSize = bucketSize;
this.tokens = bucketSize;
this.refillRate = refillRate;
this.lastRefill = Date.now();
}
private refill() {
const now = Date.now();
const elapsed = (now - this.lastRefill) / 1000;
const tokensToAdd = Math.floor(elapsed * this.refillRate);
if (tokensToAdd > 0) {
this.tokens = Math.min(this.bucketSize, this.tokens + tokensToAdd);
this.lastRefill = now;
}
}
public consume(): boolean {
this.refill();
if (this.tokens > 0) {
this.tokens -= 1;
return true;
} else {
return false;
}
}
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
May 26, 2024