Created
February 23, 2018 15:49
-
-
Save kendru/f8336f8647315878f5af191157d1a73b to your computer and use it in GitHub Desktop.
Simple token bucket implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Bucket { | |
constructor(size, per) { | |
this.per = per; | |
this.size = size; | |
this.lastFilled = Math.floor(Date.now() / 1000); | |
this.tokens = size; | |
} | |
take() { | |
this.refill(); | |
if (this.tokens <= 0) { | |
return false; | |
} | |
this.tokens--; | |
return true; | |
} | |
refill() { | |
const now = Math.floor(Date.now() / 1000); | |
const rate = (now - this.lastFilled) / this.per; | |
console.log('Rate: ', rate); | |
this.tokens = Math.min(this.size, this.tokens + Math.floor(rate * this.size)); | |
this.lastFilled = now; | |
console.log('Refilled to ' + this.tokens); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment