Skip to content

Instantly share code, notes, and snippets.

@AddyM
Forked from anonymous/hit-counter.js
Created March 5, 2017 17:35
Show Gist options
  • Save AddyM/e436155946f75b344abfaae0c72568b9 to your computer and use it in GitHub Desktop.
Save AddyM/e436155946f75b344abfaae0c72568b9 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;
@AddyM
Copy link
Author

AddyM commented Mar 5, 2017

if you are building a website, how do you count the number of visitors for the past 1 minute?
Above is the basic implementation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment