1. /**
  2. * Instruments list operations with rate limiting.
  3. *
  4. * @param {function} listOperation - The function to instrument (e.g., add, remove, get).
  5. * @param {number} maxRequestsPerSecond - The maximum number of requests allowed per second.
  6. * @returns {function} - A wrapped function that applies rate limiting.
  7. */
  8. function rateLimitListOperations(listOperation, maxRequestsPerSecond) {
  9. let queue = [];
  10. let lastExecutionTime = 0;
  11. async function executeWithRateLimit() {
  12. if (queue.length > 0) {
  13. const now = Date.now();
  14. const timeSinceLastExecution = now - lastExecutionTime;
  15. const delay = Math.max(0, 1000 / (maxRequestsPerSecond - Math.floor(timeSinceLastExecution / 1000))); // Calculate delay
  16. await new Promise(resolve => setTimeout(resolve, delay));
  17. const nextOperation = queue.shift();
  18. return nextOperation();
  19. }
  20. return Promise.resolve(listOperation()); // Execute if queue is empty
  21. }
  22. return async function (...args) {
  23. return executeWithRateLimit().then(result => {
  24. lastExecutionTime = Date.now();
  25. queue.push(() => result);
  26. return result;
  27. });
  28. };
  29. }

Add your comment