-
-
Save AddyM/e436155946f75b344abfaae0c72568b9 to your computer and use it in GitHub Desktop.
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 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
if you are building a website, how do you count the number of visitors for the past 1 minute?
Above is the basic implementation