Last active
June 8, 2018 13:18
-
-
Save RickWong/4e3425e9b3936dbc6bdad164f2e6fced to your computer and use it in GitHub Desktop.
InMemoryCounter
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 InMemoryCounter { | |
constructor({ seconds = 1, rolling = true, max }) { | |
this.seconds = seconds; | |
this.rolling = rolling; | |
this.max = max; | |
if (!this.rolling) { | |
this.interval = setInterval(() => { | |
this.counter = 0; | |
}, this.seconds * 1000); | |
} | |
this.counter = 0; | |
} | |
increment() { | |
if (this.max !== undefined && this.counter >= this.max) { | |
return false; | |
} | |
this.counter++; | |
if (this.rolling) { | |
setTimeout(() => { | |
this.counter = Math.max(0, this.counter - 1); | |
}, this.seconds * 1000); | |
} | |
return true; | |
} | |
count() { | |
return this.counter; | |
} | |
remaining() { | |
if (this.max === undefined) { | |
throw new Error("Missing 'max' config"); | |
} | |
return Math.max(0, this.max - this.counter); | |
} | |
stop() { | |
clearInterval(this.interval); | |
} | |
} | |
// Use InMemoryCounter as a rate limiter. 10 increments per 2 seconds rolling. | |
const rateLimiter = new InMemoryCounter({ seconds: 2, rolling: true, max: 10 }); | |
rateLimiter.increment(); // true | |
rateLimiter.remaining(); // 9 | |
// Use InMemoryCounter as an FPS counter. Hard reset every second. | |
const fpsCounter = new InMemoryCounter({ seconds: 1, rolling: false }); | |
fpsCounter.increment(); // true | |
fpsCounter.count(); // 1 | |
fpsCounter.stop(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment