Middle
function createRateLimiter(limit, interval) {} // Tests const limiter = createRateLimiter(2, 100); let count = 0; const fn = () => { count++ console.log(count) }; limiter(fn); // count = 1 limiter(fn); // count = 2 limiter(fn); // Ignored (limit 2/100ms) setTimeout(() => limiter(fn), 150); // count = 3 (more than 100ms passed)
sobes.tech AI
Answer from AI
The createRateLimiter function should return a call limiter function that allows the passed function to be called no more than limit times within an interval in milliseconds. If the limit is exceeded, the call is ignored.
Example implementation in JavaScript:
function createRateLimiter(limit, interval) {
let calls = 0;
let queue = [];
setInterval(() => {
calls = 0;
while (calls < limit && queue.length > 0) {
const fn = queue.shift();
fn();
calls++;
}
}, interval);
return function(fn) {
if (calls < limit) {
calls++;
fn();
} else {
// Ignore the call, do not add to queue
}
};
}
// Tests
const limiter = createRateLimiter(2, 100);
let count = 0;
const fn = () => {
count++;
console.log(count);
};
limiter(fn); // count = 1
limiter(fn); // count = 2
limiter(fn); // Ignored (limit 2/100ms)
setTimeout(() => limiter(fn), 150); // count = 3 (more than 100ms passed)
In this implementation, calls exceeding the limit are simply ignored, as specified in the condition.