Skip to content

Commit

Permalink
fix: support avg queries (#2026)
Browse files Browse the repository at this point in the history
Co-authored-by: Sebastian <sebastian@aam-digital.com>
  • Loading branch information
TheSlimvReal and sleidig authored Nov 14, 2023
1 parent 7cf1d82 commit 731da68
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
28 changes: 28 additions & 0 deletions src/app/core/export/query.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,34 @@ describe("QueryService", () => {
expect(res).toBe(3);
});

it("should calculate the average of values", () => {
const data = [
{ a: 5, b: 2 },
{ b: "11" },
{ b: -1 },
{ b: 100 },
{ a: "invalid" },
];

let res = service.queryData("a:avg", undefined, undefined, data);
expect(res).toBe("5");

// Returns valid number if no values are available
res = service.queryData("a:avg", undefined, undefined, [{ b: 1 }]);
expect(res).toBe("0");

// Numbers are fixed to provided decimals
res = service.queryData("a:avg(2)", undefined, undefined, [
{ a: 3 },
{ a: 2 },
]);
expect(res).toBe("2.50");

// Handles 0 correctly
res = service.queryData("a:avg", undefined, undefined, [{ a: 0 }]);
expect(res).toBe("0");
});

function queryData(query: string, from?: Date, to?: Date, data?: any) {
return service
.cacheRequiredData(query, from, to)
Expand Down
22 changes: 21 additions & 1 deletion src/app/core/export/query.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ export class QueryService {
unique: this.unique,
count: this.count,
sum: this.sum,
avg: this.avg,
addPrefix: this.addPrefix,
toEntities: this.toEntities.bind(this),
getRelated: this.getRelated.bind(this),
Expand Down Expand Up @@ -238,7 +239,7 @@ export class QueryService {
/**
* Returns the (integer) sum of the provided array.
* It can also handle integers in strings, e.g. "3"
* @param data and integer array
* @param data an integer array
* @private
*/
private sum(data: any[]): number {
Expand All @@ -248,6 +249,25 @@ export class QueryService {
}, 0);
}

/**
* Returns the avg of the provided array as string.
* It can also handle integers in strings, e.g. "3".
* The average is only calculated if the value exists and is a valid number.
* @param data an integer array
* @param decimals the amount of decimals for the result, default 0
* @private
*/
private avg(data: any[], decimals = 0): string {
const numbers = data
.map((d) => Number.parseInt(d))
.filter((i) => !Number.isNaN(i));
const result =
numbers.length === 0
? 0
: numbers.reduce((i, sum) => sum + i, 0) / numbers.length;
return result.toFixed(decimals);
}

/**
* Turns a list of ids (with the entity prefix) into a list of entities
* @param ids the array of ids with entity prefix
Expand Down

0 comments on commit 731da68

Please sign in to comment.