/**
* Flags anomalies in a collection based on rate limiting.
*
* @param {Array<Object>} collection - The collection of data to analyze.
* @param {number} rateLimit - The maximum number of items allowed within a time window (in milliseconds).
* @param {number} windowSize - The size of the time window in milliseconds.
* @returns {Array<Object>} - The original collection with anomaly flags added.
*/
function flagAnomalies(collection, rateLimit, windowSize) {
const anomalyFlags = [];
const requestTimestamps = [];
collection.forEach(item => {
const timestamp = Date.now();
// Remove outdated timestamps
while (requestTimestamps.length > 0 && requestTimestamps[0] <= timestamp - windowSize) {
requestTimestamps.shift(); // Remove the oldest timestamp
}
// Check if the rate limit is exceeded
if (requestTimestamps.length >= rateLimit) {
anomalyFlags.push({ item: item, reason: 'Rate Limit Exceeded' });
}
requestTimestamps.push(timestamp);
});
// Add anomaly flags to the original collection
const flaggedCollection = collection.map(item => {
if (anomalyFlags.some(flag => flag.item === item)) {
return { ...item, anomalyFlag: anomalyFlags.find(flag => flag.item === item) };
}
return item;
});
return flaggedCollection;
}
Add your comment