src/features/reports/progress-sort.ts
Linked repository file from this build.
export type ProgressGroup = {
key: string;
label: string;
total: number;
completed: number;
error: number;
};
export type MonthChartSort = "newest" | "oldest" | "least-complete" | "most-complete";
export type CountyChartSort =
| "name-asc"
| "name-desc"
| "total-asc"
| "total-desc"
| "error-asc"
| "error-desc";
export const monthChartSorts: { value: MonthChartSort; label: string }[] = [
{ value: "newest", label: "Newest first" },
{ value: "oldest", label: "Oldest first" },
{ value: "least-complete", label: "Least complete" },
{ value: "most-complete", label: "Most complete" },
];
export const countyChartSorts: { value: CountyChartSort; label: string }[] = [
{ value: "name-asc", label: "A to Z" },
{ value: "name-desc", label: "Z to A" },
{ value: "total-asc", label: "Fewest reviews" },
{ value: "total-desc", label: "Most reviews" },
{ value: "error-asc", label: "Fewest errors" },
{ value: "error-desc", label: "Most errors" },
];
function nextChartSort<T extends string>(options: { value: T }[], current: T) {
const index = options.findIndex((option) => option.value === current);
return options[(index + 1) % options.length].value;
}
export function nextMonthChartSort(current: MonthChartSort) {
return nextChartSort(monthChartSorts, current);
}
export function nextCountyChartSort(current: CountyChartSort) {
return nextChartSort(countyChartSorts, current);
}
function completion(group: ProgressGroup) {
return group.total ? group.completed / group.total : 0;
}
export function sortMonthGroups<T extends ProgressGroup>(groups: T[], sort: MonthChartSort) {
return [...groups].sort((left, right) => {
if (sort === "oldest") return left.key.localeCompare(right.key);
if (sort === "newest") return right.key.localeCompare(left.key);
const delta = completion(left) - completion(right);
if (sort === "least-complete") return delta || right.key.localeCompare(left.key);
return -delta || left.key.localeCompare(right.key);
});
}
export function sortCountyGroups<T extends ProgressGroup>(groups: T[], sort: CountyChartSort) {
return [...groups].sort((left, right) => {
if (sort === "name-asc") return left.label.localeCompare(right.label);
if (sort === "name-desc") return right.label.localeCompare(left.label);
if (sort === "total-asc")
return left.total - right.total || left.label.localeCompare(right.label);
if (sort === "total-desc")
return right.total - left.total || left.label.localeCompare(right.label);
if (sort === "error-asc")
return left.error - right.error || left.label.localeCompare(right.label);
return right.error - left.error || left.label.localeCompare(right.label);
});
}