/**
* Extends existing dataset logic with rate limiting.
*
* @param {function} originalFunction The original function to be rate limited.
* @param {number} maxRequestsPerSecond The maximum number of requests allowed per second.
* @returns {function} A rate-limited version of the original function.
*/
function rateLimit(originalFunction, maxRequestsPerSecond) {
let queue = []; // Queue to hold requests
let running = 0; // Number of currently executing requests
let lastExecutionTime = 0; // Time of the last execution
/**
* Rate-limited version of the original function.
* @param {...any} args Arguments to pass to the original function.
* @returns {Promise<any>} A promise that resolves with the result of the original function.
*/
return async function (...args) {
return new Promise((resolve, reject) => {
const now = Date.now();
// Check if we're exceeding the rate limit
if (running >= maxRequestsPerSecond) {
// Add the request to the queue
queue.push({ args, resolve, reject });
return;
}
// Start the request
running++;
const startTime = now;
// Execute the original function
originalFunction(...args)
.then(result => {
// Resolve the promise with the result
resolve(result);
})
.catch(error => {
// Reject the promise with the error
reject(error);
})
.finally(() => {
// Decrement the number of running requests
running--;
// Process the queue
processQueue();
});
});
};
/**
* Processes the request queue.
*/
function processQueue() {
while (queue.length > 0) {
const { args, resolve, reject } = queue.shift();
const now = Date.now();
// Check if the rate limit has been exceeded
if (now - lastExecutionTime >= 1000) {
// Reset the rate limit
running = 0;
lastExecutionTime = now;
}
}
}
}
Add your comment