Add sorting to detail breakdown tables

This commit is contained in:
2026-04-28 13:40:45 +08:00
parent ab915e9292
commit e8a66cf180
3 changed files with 86 additions and 8 deletions

23
lib/detail-sort.test.ts Normal file
View File

@@ -0,0 +1,23 @@
import { describe, expect, test } from "bun:test";
import { sortDetailBreakdown } from "./detail-sort";
describe("sortDetailBreakdown", () => {
const rows = [
{ name: "beta", calls: 2, total_tokens: 100, quota: 500 },
{ name: "alpha", calls: 5, total_tokens: 100, quota: 300 },
{ name: "gamma", calls: 1, total_tokens: 300, quota: 100 },
];
test("sorts by the selected numeric field without mutating the source rows", () => {
const sorted = sortDetailBreakdown(rows, "quota", false);
expect(sorted.map((row) => row.name)).toEqual(["beta", "alpha", "gamma"]);
expect(rows.map((row) => row.name)).toEqual(["beta", "alpha", "gamma"]);
});
test("uses name as a stable tie-breaker", () => {
const sorted = sortDetailBreakdown(rows, "total_tokens", false);
expect(sorted.map((row) => row.name)).toEqual(["gamma", "alpha", "beta"]);
});
});

20
lib/detail-sort.ts Normal file
View File

@@ -0,0 +1,20 @@
export interface DetailBreakdownItem {
name: string;
calls: number;
total_tokens: number;
quota: number;
}
export type DetailBreakdownSortKey = "calls" | "total_tokens" | "quota";
export function sortDetailBreakdown(
items: DetailBreakdownItem[],
sortKey: DetailBreakdownSortKey,
sortAsc: boolean
): DetailBreakdownItem[] {
return [...items].sort((a, b) => {
const diff = a[sortKey] - b[sortKey];
if (diff !== 0) return sortAsc ? diff : -diff;
return a.name.localeCompare(b.name);
});
}