在这段生成的发票汇总代码成为公开库函数前,对它进行审查。
解析不可信的发票数组,验证每条记录,并为每种输入返回稳定的 InvoiceSummary;不要排序,也不要暴露意外的推断 API 变化。
TypeScript
type Invoice = { id: string; cents: number };
type InvoiceSummary = { count: number; totalCents: number };
export function summarize(raw: string) {
const invoices = JSON.parse(raw) as Invoice[];
const cents = [];
for (const invoice of invoices) {
cents.push(invoice.cents);
}
cents.sort((left, right) => left - right);
const totalCents = cents.reduce((sum, value) => sum + value, 0);
if (cents.length === 0) {
return null;
}
return { count: cents.length, totalCents };
}
生成代码仅作示例,不代表任何特定模型