Skip to content

Commit 7242a9a

Browse files
authored
[data grid] Fix avg aggregation when the average is zero (mui#22652)
1 parent 9024c41 commit 7242a9a

2 files changed

Lines changed: 21 additions & 23 deletions

File tree

packages/x-data-grid-premium/src/hooks/features/aggregation/gridAggregationFunctions.ts

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,6 @@ const sumAgg: GridAggregationFunction<unknown, number> = {
1818

1919
const avgAgg: GridAggregationFunction<unknown, number> = {
2020
apply: ({ values }) => {
21-
if (values.length === 0) {
22-
return null;
23-
}
24-
2521
let sum = 0;
2622
let valuesCount = 0;
2723
for (let i = 0; i < values.length; i += 1) {
@@ -32,7 +28,7 @@ const avgAgg: GridAggregationFunction<unknown, number> = {
3228
}
3329
}
3430

35-
if (sum === 0) {
31+
if (valuesCount === 0) {
3632
return null;
3733
}
3834

packages/x-data-grid-premium/src/tests/aggregation.DataGridPremium.test.tsx

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1050,31 +1050,33 @@ describe('<DataGridPremium /> - Aggregation', () => {
10501050
});
10511051

10521052
describe('`avg`', () => {
1053+
const applyAvgAggregation = (values: unknown[]) =>
1054+
GRID_AGGREGATION_FUNCTIONS.avg.apply({
1055+
values,
1056+
field: 'value',
1057+
groupId: 0,
1058+
});
1059+
10531060
it('should work with numbers', () => {
1054-
expect(
1055-
GRID_AGGREGATION_FUNCTIONS.avg.apply(
1056-
{
1057-
values: [0, 10, 12, 23],
1058-
field: 'value',
1059-
groupId: 0,
1060-
},
1061-
apiRef.current!,
1062-
),
1063-
).to.equal(11.25);
1061+
expect(applyAvgAggregation([0, 10, 12, 23])).to.equal(11.25);
10641062
});
10651063

10661064
it('should ignore non-numbers', () => {
10671065
expect(
1068-
GRID_AGGREGATION_FUNCTIONS.avg.apply(
1069-
{
1070-
values: [0, 10, 12, 23, 'a', '', undefined, null, NaN, {}, true],
1071-
field: 'value',
1072-
groupId: 0,
1073-
},
1074-
apiRef.current!,
1075-
),
1066+
applyAvgAggregation([0, 10, 12, 23, 'a', '', undefined, null, NaN, {}, true]),
10761067
).to.equal(11.25);
10771068
});
1069+
1070+
it('should return 0 when the numeric values average to 0', () => {
1071+
expect(applyAvgAggregation([-5, 5])).to.equal(0);
1072+
expect(applyAvgAggregation([0, 0])).to.equal(0);
1073+
expect(applyAvgAggregation([-10, 4, 6])).to.equal(0);
1074+
expect(applyAvgAggregation([0, 'a', '', undefined, null, NaN, {}, true])).to.equal(0);
1075+
});
1076+
1077+
it('should return null when there are no numeric values', () => {
1078+
expect(applyAvgAggregation(['a', '', undefined, null, NaN, {}, true])).to.equal(null);
1079+
});
10781080
});
10791081

10801082
describe('`size`', () => {

0 commit comments

Comments
 (0)