/**
* Rate Limited Time Value Exporter
*
* Exports time values with rate limiting to prevent abuse.
*
* @param {Function} timeValueGenerator - A function that generates the time value.
* @param {number} rateLimit - The maximum number of exports allowed per time unit (e.g., 10 exports per second).
* @param {number} timeUnit - The time unit for the rate limit (e.g., 1000 for milliseconds).
* @returns {Generator} A generator that yields time values with rate limiting.
*/
function* rateLimitedTimeExporter(timeValueGenerator, rateLimit, timeUnit) {
let queue = []; // Queue of time values to be exported.
let running = 0; // Number of exports currently in progress.
let lastExportTime = 0; // Timestamp of the last export.
async function exportTimeValue() {
if (queue.length > 0 && running < rateLimit) {
const timeValue = queue.shift();
running++;
const now = Date.now();
if (now - lastExportTime >= timeUnit) {
lastExportTime = now;
}
console.log("Exporting time value:", timeValue);
running--;
yield timeValue;
// Schedule the next export.
setTimeout(exportTimeValue, 0); // Use setTimeout(..., 0) for minimal delay
}
}
// Add the time values to the queue.
const timeValues = timeValueGenerator();
for (const timeValue of timeValues) {
queue.push(timeValue);
}
// Start the export process.
await exportTimeValue();
}
export default rateLimitedTimeExporter;
Add your comment