Trim zeroes at the edge of datapoints in chart data

This commit is contained in:
nise.moe 2024-02-19 15:59:52 +01:00
parent da8bf771a8
commit 45b4334011

View File

@ -1,4 +1,4 @@
import {ChangeDetectionStrategy, Component, Input, OnChanges, SimpleChanges} from '@angular/core';
import {ChangeDetectionStrategy, Component, Input, OnChanges} from '@angular/core';
import {DecimalPipe, NgForOf} from "@angular/common";
import {ChartConfiguration, ChartData, DefaultDataPoint} from "chart.js";
import {NgChartsModule} from "ng2-charts";
@ -78,6 +78,23 @@ export class ChartComponent implements OnChanges {
return Object.entries(statistics).map(([name, value]) => ({ name, value }));
}
/**
* Removes zeros from the start and end of the array, used for charts.
*/
trimEdgeZeros(dataPoints: { value: number, count: number }[]): { value: number, count: number }[] {
let startIndex = 0;
while (startIndex < dataPoints.length && dataPoints[startIndex].count === 0) {
startIndex++;
}
let endIndex = dataPoints.length - 1;
while (endIndex >= 0 && dataPoints[endIndex].count === 0) {
endIndex--;
}
return dataPoints.slice(startIndex, endIndex + 1);
}
buildChartData(): ChartData<"bar", DefaultDataPoint<"bar">, any> {
let chartData = this.data;
@ -107,6 +124,8 @@ export class ChartComponent implements OnChanges {
}
}
dataPoints = this.trimEdgeZeros(dataPoints);
const total = dataPoints.reduce((acc, curr) => acc + curr.count, 0);
const labels = this.groupData ? dataPoints.map(({ value }) => `${value}ms to ${value + 2}ms`) : dataPoints.map(({ value }) => `${value}ms`);