From 5ec06bab571fa92c4c3bc3ba772cc8ca23d27ab2 Mon Sep 17 00:00:00 2001 From: wolfy01 <45273698+wolfy01@users.noreply.github.com> Date: Tue, 7 Apr 2020 01:59:49 -0400 Subject: [PATCH] Create Ratelimit.js --- src/Ratelimit.js | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/Ratelimit.js diff --git a/src/Ratelimit.js b/src/Ratelimit.js new file mode 100644 index 0000000..f43157d --- /dev/null +++ b/src/Ratelimit.js @@ -0,0 +1,40 @@ + +var RateLimit = function(interval_ms) { + this._interval_ms = interval_ms || 0; // (0 means no limit) + this._after = 0; +}; + +RateLimit.prototype.attempt = function(time) { + var time = time || Date.now(); + if(time < this._after) return false; + this._after = time + this._interval_ms; + return true; +}; + +RateLimit.prototype.setInterval = function(interval_ms) { + this._after += interval_ms - this._interval_ms; + this._interval_ms = interval_ms; +}; + +var RateLimitChain = function(num, interval_ms) { + this.setNumAndInterval(num, interval_ms); +}; + +RateLimitChain.prototype.attempt = function(time) { + var time = time || Date.now(); + for(var i = 0; i < this._chain.length; i++) { + if(this._chain[i].attempt(time)) return true; + } + return false; +}; + +RateLimitChain.prototype.setNumAndInterval = function(num, interval_ms) { + this._chain = []; + for(var i = 0; i < num; i++) { + this._chain.push(new RateLimit(interval_ms)); + } +}; + +var exports = typeof module !== "undefined" ? module.exports : this; +exports.RateLimit = RateLimit; +exports.RateLimitChain = RateLimitChain;