实现说明
WeightTable承担全部实现。
本示例的循环部分是 for (const { key, weight } of entries)。
演示用的数据放在这几个模块级绑定中:table。
使用要点
- 直接运行文件,输出会带上标签,比如
cpu total:、gpu total:、input untouched:——输出的每一行都能指回产生它的那次调用。
常见问题
有语言之外需要解析的导入吗?
没有。每个导入都解析到语言自带的模块。 文件的状态由几个模块级绑定持有:table。
核心语句
return this.byKey.get(key) ?? 0;
map.set(key, (map.get(key) ?? 0) + weight);
const map = new Map<string, number>();
代码示例
type Entry = { key: string; weight: number };
// The factory treats both parameters as read-only views:
// the class below re-derives its own structures instead of mutating inputs.
class WeightTable {
private readonly byKey: ReadonlyMap<string, number>;
constructor(entries: readonly Entry[]) {
const map = new Map<string, number>();
for (const { key, weight } of entries) {
map.set(key, (map.get(key) ?? 0) + weight);
}
this.byKey = map;
}
weightOf(key: string): number {
return this.byKey.get(key) ?? 0;
}
}
const shared: readonly Entry[] = [
{ key: 'cpu', weight: 2 },
{ key: 'gpu', weight: 5 },
{ key: 'cpu', weight: 1 },
];
const table = new WeightTable(shared);
console.log('cpu total:', table.weightOf('cpu'));
console.log('gpu total:', table.weightOf('gpu'));
console.log('input untouched:', shared.length, shared[0].weight);
// These fail compilation — readonly hides the mutating methods:
// shared.sort((a, b) => b.weight - a.weight);
// shared.push({ key: 'io', weight: 3 });