/**
* Flags anomalous timestamps in an array of timestamps.
*
* @param {Array<number>} timestamps An array of timestamp values (e.g., milliseconds since epoch).
* @param {number} anomalyThreshold The number of standard deviations from the mean to consider a timestamp anomalous.
* @returns {Array<number>} An array of indices of anomalous timestamps. Returns an empty array if input is invalid.
*/
function flagTimestampAnomalies(timestamps, anomalyThreshold = 3) {
if (!Array.isArray(timestamps) || timestamps.length === 0) {
return []; // Handle invalid input
}
const n = timestamps.length;
if (typeof anomalyThreshold !== 'number' || anomalyThreshold <= 0) {
anomalyThreshold = 3; //Use default if invalid
}
// Calculate the mean and standard deviation
let sum = 0;
for (let i = 0; i < n; i++) {
if (typeof timestamps[i] !== 'number') {
continue; // Skip non-numeric values
}
sum += timestamps[i];
}
const mean = sum / n;
let sumOfSquares = 0;
for (let i = 0; i < n; i++) {
if (typeof timestamps[i] !== 'number') {
continue; // Skip non-numeric values
}
sumOfSquares += Math.pow(timestamps[i] - mean, 2);
}
const stdDev = Math.sqrt(sumOfSquares / n);
// Identify anomalous timestamps
const anomalousIndices = [];
for (let i = 0; i < n; i++) {
if (typeof timestamps[i] !== 'number') {
continue; // Skip non-numeric values
}
const zScore = Math.abs((timestamps[i] - mean) / stdDev);
if (zScore > anomalyThreshold) {
anomalousIndices.push(i);
}
}
return anomalousIndices;
}
Add your comment