Skip to content

Instantly share code, notes, and snippets.

@kendru
Created February 23, 2018 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kendru/f8336f8647315878f5af191157d1a73b to your computer and use it in GitHub Desktop.
Save kendru/f8336f8647315878f5af191157d1a73b to your computer and use it in GitHub Desktop.
Simple token bucket implementation
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