实现说明
底层就是函数 quote、discountView。
使用要点
- 跑完文件,输出里会留下标记——
quote total cents:、visible rates:、owned copy length:。
常见问题
除了语言运行时还需要什么准备?
什么都不需要——语言运行时是唯一要求。 文件在加载时定义 quote、discountView。
主签名形如 function quote(lines: readonly CartLine[], rates: ReadonlyMap<string, number>)
核心语句
return lines.reduce((sum, line) => sum + line.qty * line.unitCents * (rates.get(line.sku) ?? 1), 0);
const discounts = new Map<string, number>([
['pen', 0.9],
['notebook', 1],
]);
代码示例
// Public signatures take readonly collection types: callers get no write methods,
// the service keeps the full Map/array internally - the ownership boundary lives in the types
interface CartLine {
sku: string;
qty: number;
unitCents: number;
}
const discounts = new Map<string, number>([
['pen', 0.9],
['notebook', 1],
]);
function quote(lines: readonly CartLine[], rates: ReadonlyMap<string, number>): number {
return lines.reduce((sum, line) => sum + line.qty * line.unitCents * (rates.get(line.sku) ?? 1), 0);
}
// The returned view is read-only outside: set/delete do not exist on the type
function discountView(): ReadonlyMap<string, number> {
return discounts;
}
const cart: readonly CartLine[] = [
{ sku: 'pen', qty: 2, unitCents: 250 },
{ sku: 'notebook', qty: 1, unitCents: 880 },
];
// cart.push(...) and discounts.set(...) are compile errors through these references
console.log('quote total cents:', quote(cart, discounts));
console.log(
'visible rates:',
[...discountView().entries()].map(([k, v]) => `${k}=${v}`).join(' '),
);
// Callers who need to mutate must copy explicitly - ownership stays clear
const owned = [...cart];
owned.push({ sku: 'eraser', qty: 3, unitCents: 120 });
console.log('owned copy length:', owned.length, 'cart still:', cart.length);