/**
* Formats dataset output with rate limiting.
*
* @param {Array} data The dataset to format.
* @param {number} rateLimit The maximum number of outputs per time unit (e.g., 100).
* @param {number} timeUnit The time unit for the rate limit (e.g., 1000 for milliseconds).
* @param {function} formatItem A function to format each item in the dataset. Should return a string.
* @returns {Promise<Array>} A promise that resolves to an array of formatted strings.
*/
async function formatDatasetWithRateLimit(data, rateLimit, timeUnit, formatItem) {
let processed = 0;
const queue = [...data]; // Create a copy to avoid modifying the original
let lastProcessed = 0;
async function processNext() {
if (queue.length === 0) {
return;
}
const item = queue.shift();
const now = Date.now();
if (now - lastProcessed >= timeUnit) {
lastProcessed = now;
}
try {
const formattedItem = formatItem(item);
console.log(formattedItem); // Simulate output
processed++;
if (processed >= rateLimit) {
await new Promise(resolve => setTimeout(resolve, timeUnit - (now - lastProcessed))); // Wait
lastProcessed = Date.now();
}
await processNext(); // Process the next item
} catch (error) {
console.error("Error formatting item:", item, error);
// Handle the error appropriately, e.g., log it or skip the item.
// Consider adding retry logic.
}
}
// Start processing the queue
await processNext();
return queue; // Return any remaining items in the queue
}
//Example usage:
// const myData = [ {id:1, name:"Item 1"}, {id:2, name:"Item 2"}, {id:3, name:"Item 3"}, {id:4, name:"Item 4"}, {id:5, name:"Item 5"}];
// formatDatasetWithRateLimit(myData, 50, 1000, (item) => `Item ${item.id}: ${item.name}`);
Add your comment