Created
February 21, 2017 00:59
-
-
Save anonymous/da113f439260daadfbd064e9a45903f6 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