// ════════════════════════════════════════════════════════════ // inventory —— 库存(被 orders 调用) // 练习:/stock/ 搜索、]m [m 方法跳转、gA 查看引用 // ════════════════════════════════════════════════════════════ const stock = new Map([ ["apple", 40], ["banana", 60], ["milk", 20], ["bread", 15], ["egg", 120], ["cheese", 8], ]); export class StockError extends Error {} export function available(productId: string): number { return stock.get(productId) ?? 0; } // 预占库存:不够就抛 StockError —— cif 改函数体 / ci" 改错误消息的靶子 export function reserve(productId: string, quantity: number): void { const left = available(productId); if (quantity > left) { throw new StockError(`Not enough stock for ${productId} (need ${quantity}, have ${left})`); } stock.set(productId, left - quantity); } export function release(productId: string, quantity: number): void { stock.set(productId, available(productId) + quantity); } export function stockReport(): string[] { const rows: string[] = []; for (const [id, left] of stock) { rows.push(`${id.padEnd(8)} ${String(left).padStart(3)} left`); } return rows; }