UNPKG

820 BJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3class TokenBucket {
4 constructor({ refillPeriod, refillCount, capacity }) {
5 this.lastTime = Date.now();
6 this.capacity = (typeof capacity !== 'undefined') ? capacity : refillCount;
7 this.left = this.capacity;
8 this.refillRate = refillCount / refillPeriod;
9 }
10 take(count = 1) {
11 const now = Date.now();
12 const delta = Math.max(now - this.lastTime, 0);
13 const amount = delta * this.refillRate;
14 this.lastTime = now;
15 this.left = Math.min(this.left + amount, this.capacity);
16 if (this.left < count) {
17 return false;
18 }
19 this.left -= count;
20 return true;
21 }
22}
23exports.default = TokenBucket;
24//# sourceMappingURL=token-bucket.js.map
\No newline at end of file