1. /**
  2. * Flags anomalies in a collection based on rate limiting.
  3. *
  4. * @param {Array<Object>} collection - The collection of data to analyze.
  5. * @param {number} rateLimit - The maximum number of items allowed within a time window (in milliseconds).
  6. * @param {number} windowSize - The size of the time window in milliseconds.
  7. * @returns {Array<Object>} - The original collection with anomaly flags added.
  8. */
  9. function flagAnomalies(collection, rateLimit, windowSize) {
  10. const anomalyFlags = [];
  11. const requestTimestamps = [];
  12. collection.forEach(item => {
  13. const timestamp = Date.now();
  14. // Remove outdated timestamps
  15. while (requestTimestamps.length > 0 && requestTimestamps[0] <= timestamp - windowSize) {
  16. requestTimestamps.shift(); // Remove the oldest timestamp
  17. }
  18. // Check if the rate limit is exceeded
  19. if (requestTimestamps.length >= rateLimit) {
  20. anomalyFlags.push({ item: item, reason: 'Rate Limit Exceeded' });
  21. }
  22. requestTimestamps.push(timestamp);
  23. });
  24. // Add anomaly flags to the original collection
  25. const flaggedCollection = collection.map(item => {
  26. if (anomalyFlags.some(flag => flag.item === item)) {
  27. return { ...item, anomalyFlag: anomalyFlags.find(flag => flag.item === item) };
  28. }
  29. return item;
  30. });
  31. return flaggedCollection;
  32. }

Add your comment