Skip to content

Commit

Permalink
[Feature] Sort report totals by counts
Browse files Browse the repository at this point in the history
  • Loading branch information
levinmr committed Aug 21, 2024
1 parent a02ce44 commit bf781a3
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
6 changes: 6 additions & 0 deletions reports/usa.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@
}
],
"orderBys": [
{
"dimension": {
"dimensionName": "date"
},
"desc": true
},
{
"metric": {
"metricName": "totalUsers"
Expand Down
7 changes: 6 additions & 1 deletion src/process_results/result_totals_calculator.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const calculateTotals = (result, options = {}) => {
column,
result,
});
totals[`by_${column}`] = _sortObjectByValues(totals[`by_${column}`]);
}
}

Expand Down Expand Up @@ -92,10 +93,14 @@ const _sumMetricByColumn = ({ metric, result, column }) => {
const category = row[column];
const count = parseInt(row[metric]);
categories[category] = (categories[category] || 0) + count;
return categories;
return _sortObjectByValues(categories);
}, {});
};

const _sortObjectByValues = (object) => {
return Object.fromEntries(Object.entries(object).sort((a, b) => b[1] - a[1]));
};

const _sumVisitsByCategoryWithDimension = ({ result, column, dimension }) => {
return result.data.reduce((categories, row) => {
const parentCategory = row[column];
Expand Down
20 changes: 20 additions & 0 deletions test/process_results/result_totals_calculator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,16 @@ describe("ResultTotalsCalculator", () => {
it("should compute totals for desktop devices", () => {
expect(totals.by_device.desktop).to.equal(300 + 600);
});

it("sorts totals by visit count", () => {
expect(Object.entries(totals.by_device)).to.deep.equal(
Object.entries({
desktop: 900,
tablet: 700,
mobile: 500,
}),
);
});
});

describe("and there are multiple columns being totalled", () => {
Expand Down Expand Up @@ -261,6 +271,16 @@ describe("ResultTotalsCalculator", () => {
it("should compute user totals for desktop devices", () => {
expect(totals.by_device.desktop).to.equal(300 + 600);
});

it("sorts totals by user count", () => {
expect(Object.entries(totals.by_device)).to.deep.equal(
Object.entries({
desktop: 900,
tablet: 700,
mobile: 500,
}),
);
});
});

describe("and there are multiple columns being totalled", () => {
Expand Down

0 comments on commit bf781a3

Please sign in to comment.