Skip to content

Instantly share code, notes, and snippets.

Created February 21, 2017 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/da113f439260daadfbd064e9a45903f6 to your computer and use it in GitHub Desktop.
Save anonymous/da113f439260daadfbd064e9a45903f6 to your computer and use it in GitHub Desktop.
class HitCounter {
constructor(interval) {
this.interval = interval;
this.buckets = Array(60 / this.interval).fill(0);
this.bucketCleanerInterval = this.initBucketCleaner();
}
count() {
const bucket = this.getCurrentBucket();
return this.buckets[bucket] += 1;
}
getCount() {
const bucket = this.getCurrentBucket();
return this.buckets[bucket];
}
stop() {
clearInterval(this.bucketCleanerInterval);
}
getCurrentBucket() {
const minutes = (new Date()).getMinutes();
return Math.floor(minutes / this.interval);
}
initBucketCleaner() {
const interval = 60 * this.interval * 1000 / 2;
return setInterval(this.cleanBuckets.bind(this), interval);
}
cleanBuckets() {
const bucket = this.getCurrentBucket();
for (let interval = 0; interval < this.buckets.length; interval++) {
if (interval !== bucket) this.buckets[interval] = 0;
}
}
}
module.exports = HitCounter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment