Skip to content

Instantly share code, notes, and snippets.

@superburrito superburrito/rateLimit.js
Last active Aug 6, 2019

Embed
What would you like to do?
// Queue class for performance, not critical
class Queue {
constructor() {
this.enqueue_stack = [];
this.dequeue_stack = [];
this.size = 0;
}
enqueue(val) {
this.size += 1;
this.enqueue_stack.push(val);
}
dequeue() {
if (this.size === 0) {
throw new Error("Queue is empty.");
}
if (this.dequeue_stack.length === 0) {
while (this.enqueue_stack.length > 0) {
const popped = this.enqueue_stack.pop();
this.dequeue_stack.push(popped);
}
}
this.size -= 1;
return this.dequeue_stack.pop();
}
getHead() {
if (this.size === 0) {
throw new Error("Queue is empty.");
}
if (this.dequeue_stack.length > 0) {
return this.dequeue_stack[this.dequeue_stack.length-1];
}
if (this.enqueue_stack.length > 0) {
return this.enqueue_stack[0];
}
}
}
function rateLimit(func, interval, limit) {
const queue = new Queue();
return (...args) => {
const currentTime = new Date().getTime();
// Offload expired timestamps
while (
queue.size > 0 &&
currentTime - queue.getHead() > interval
) {
queue.dequeue();
}
// Call `func` if limit hasn't been reached
if (queue.size < limit) {
queue.enqueue(currentTime)
return func(...args);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.