Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

slight code refactoring #8

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
language: node_js

node_js:
- '0.10'
- '7'
48 changes: 13 additions & 35 deletions index.js
Original file line number Diff line number Diff line change
@@ -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]);
};
}