From dd083db135b23fc6de1af6c289419e6e0b7bb28c Mon Sep 17 00:00:00 2001 From: massimo-ua Date: Sun, 13 Jan 2019 00:08:41 +0200 Subject: [PATCH 1/2] slight code refactoring --- index.js | 48 +++++++++++++----------------------------------- 1 file changed, 13 insertions(+), 35 deletions(-) diff --git a/index.js b/index.js index c4a4fb7..2e2325d 100644 --- a/index.js +++ b/index.js @@ -1,44 +1,22 @@ -module.exports = rateLimit; +module.exports = (limitCount, limitInterval, fn) => { + const fifo = []; + let count = limitCount; -function rateLimit(limitCount, limitInterval, fn) { - var fifo = []; + const delayOrIncreaseCounter = (next) => fifo.length ? next() : count += 1; - // count starts at limit - // each call of `fn` decrements the count - // it is incremented after limitInterval - var count = limitCount; - - function call_next(args) { - setTimeout(function() { - if (fifo.length > 0) { - call_next(); - } - else { - count = count + 1; - } - }, limitInterval); - - var call_args = fifo.shift(); - - // if there is no next item in the queue - // and we were called with args, trigger function immediately - if (!call_args && args) { - fn.apply(args[0], args[1]); - return; - } - - fn.apply(call_args[0], call_args[1]); + const callNext = (args) => { + setTimeout(delayOrIncreaseCounter, limitInterval, callNext); + const [ctx, params] = fifo.length ? fifo.shift() : args; + fn.apply(ctx, params); } - return function rate_limited_function() { - var ctx = this; - var args = Array.prototype.slice.call(arguments); + return function rate_limited_function(...args) { + const ctx = this; if (count <= 0) { fifo.push([ctx, args]); - return; + } else { + count -= 1; + callNext([ctx, args]); } - - count = count - 1; - call_next([ctx, args]); }; } From cde36588e8d595e00dd72ff8c7e70319fe6a88c1 Mon Sep 17 00:00:00 2001 From: massimo-ua Date: Sun, 13 Jan 2019 00:16:26 +0200 Subject: [PATCH 2/2] updated node version --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index eb3a2b9..dff2f2b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,4 @@ language: node_js node_js: - - '0.10' + - '7'