Add sorting to detail breakdown tables
This commit is contained in:
23
lib/detail-sort.test.ts
Normal file
23
lib/detail-sort.test.ts
Normal 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
20
lib/detail-sort.ts
Normal 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);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user