-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathrateLimiter.js
More file actions
45 lines (37 loc) · 1.02 KB
/
Copy pathrateLimiter.js
File metadata and controls
45 lines (37 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* rateLimiter.js
* ----------------
* Simple in-memory rate limiter using the token bucket algorithm.
* Limits how many times a function can be called in a given interval.
*
* Example:
* const limited = rateLimit(doSomething, 5, 10000); // 5 calls per 10 seconds
* limited(); // allowed
*/
function rateLimit(fn, maxCalls, interval) {
let tokens = maxCalls;
let lastRefill = Date.now();
return function (...args) {
const now = Date.now();
const elapsed = now - lastRefill;
// Refill tokens
if (elapsed > interval) {
tokens = maxCalls;
lastRefill = now;
}
if (tokens > 0) {
tokens--;
return fn.apply(this, args);
} else {
throw new Error('Rate limit exceeded. Try again later.');
}
};
}
// Example usage:
function exampleAction() {
console.log('Action executed at', new Date().toISOString());
}
const limitedAction = rateLimit(exampleAction, 3, 5000);
// Uncomment to test
// for (let i = 0; i < 5; i++) limitedAction();
module.exports = rateLimit;