Skip to content

Commit

Permalink
Fix possible division by zero in calculateAverage function
Browse files Browse the repository at this point in the history
  • Loading branch information
olezhko9 committed Apr 27, 2024
1 parent 423cba2 commit d027b54
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
8 changes: 2 additions & 6 deletions src/handlers/metricTypes/stats.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { MetricSchema, Stats } from "../../types";
import { calcMedian } from "../../utils";
import { calcMedian, calculateAverage } from "../../utils";

export class GraphiteStats implements Stats {
private count = 0;
Expand All @@ -11,13 +11,9 @@ export class GraphiteStats implements Stats {
public readonly tags?: Record<string, string>
) {}

private calculateAverage(values: number[]): number {
return values.reduce((a, b) => a + b, 0) / values.length;
}

get(): MetricSchema[] {
const median = calcMedian(this.values);
const avg = this.calculateAverage(this.values);
const avg = calculateAverage(this.values);

const time = Date.now();

Expand Down
6 changes: 6 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,9 @@ export const calcMedian = (arr: number[]): number | undefined => {
const mid = Math.floor(s.length / 2);
return s.length % 2 === 0 ? (s[mid - 1] + s[mid]) / 2 : s[mid];
};

export const calculateAverage = (arr: number[]): number => {
return arr.length
? arr.reduce((a, b) => a + b, 0) / arr.length
: 0;
};

0 comments on commit d027b54

Please sign in to comment.