1. /**
  2. * Formats dataset output with rate limiting.
  3. *
  4. * @param {Array} data The dataset to format.
  5. * @param {number} rateLimit The maximum number of outputs per time unit (e.g., 100).
  6. * @param {number} timeUnit The time unit for the rate limit (e.g., 1000 for milliseconds).
  7. * @param {function} formatItem A function to format each item in the dataset. Should return a string.
  8. * @returns {Promise<Array>} A promise that resolves to an array of formatted strings.
  9. */
  10. async function formatDatasetWithRateLimit(data, rateLimit, timeUnit, formatItem) {
  11. let processed = 0;
  12. const queue = [...data]; // Create a copy to avoid modifying the original
  13. let lastProcessed = 0;
  14. async function processNext() {
  15. if (queue.length === 0) {
  16. return;
  17. }
  18. const item = queue.shift();
  19. const now = Date.now();
  20. if (now - lastProcessed >= timeUnit) {
  21. lastProcessed = now;
  22. }
  23. try {
  24. const formattedItem = formatItem(item);
  25. console.log(formattedItem); // Simulate output
  26. processed++;
  27. if (processed >= rateLimit) {
  28. await new Promise(resolve => setTimeout(resolve, timeUnit - (now - lastProcessed))); // Wait
  29. lastProcessed = Date.now();
  30. }
  31. await processNext(); // Process the next item
  32. } catch (error) {
  33. console.error("Error formatting item:", item, error);
  34. // Handle the error appropriately, e.g., log it or skip the item.
  35. // Consider adding retry logic.
  36. }
  37. }
  38. // Start processing the queue
  39. await processNext();
  40. return queue; // Return any remaining items in the queue
  41. }
  42. //Example usage:
  43. // 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"}];
  44. // formatDatasetWithRateLimit(myData, 50, 1000, (item) => `Item ${item.id}: ${item.name}`);

Add your comment