200.Land

anomaly-detector.ts

This TypeScript code defines an AnomalyDetector class that identifies anomalies in a dataset based on the specified sensitivity level. It uses a specified numeric key to extract values from dataset objects and compute the average and standard deviation of these values to identify anomalies, which are then filtered and can be retrieved using the getAnomalies method. It leverages an interface to type the options parameter used in the constructor to instantiate the class with necessary settings.

interface AnomalyDetectorOptions<T> {
  dataset: T[];
  numericKey: keyof T;
  sensitivity: number;
}

class AnomalyDetector<T extends Record<string, any>> {
  constructor(private options: AnomalyDetectorOptions<T>) {}

  private getValues(): number[] {
    return this.options.dataset.map((item) => item[this.options.numericKey]);
  }

  public getAnomalies() {
    return this.options.dataset.filter((item) => this.hasAnomaly(item));
  }

  private hasAnomaly(item: T): boolean {
    return (
      Math.abs((item[this.options.numericKey] - this.getAvg()) / this.getStdDvtn()) > this.options.sensitivity
    );
  }

  private getAvg(): number {
    const values = this.getValues();
    return values.reduce((a, b) => a + b) / values.length;
  }

  private getStdDvtn() {
    const values = this.getValues();
    const mean = values.reduce((a, b) => a + b) / values.length;
    return Math.sqrt(values.map((x) => Math.pow(x - mean, 2)).reduce((a, b) => a + b) / values.length);
  }
}