Readonly Modifiers Keep Factory Inputs Untouched
Mark factory parameters readonly so reordering or deduplicating an input array fails to compile instead of corrupting a shared table.
Code
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 });Output
Captured from a sandboxed run of this snippet in the build pipeline.
cpu total: 3
gpu total: 5
input untouched: 3 2How this snippet works
Readonly Modifiers Keep Factory Inputs Untouched reduces to the class WeightTable.
A single loop drives the file — for (const { key, weight } of entries).
Everything operates on top-level bindings: table.
Points of care
- No outside surface: every behavior is standard library.
Using it
Look for the cpu total:, gpu total:, input untouched: prefixes when the file runs; they tie each line to its step.
Key statements
return this.byKey.get(key) ?? 0;
map.set(key, (map.get(key) ?? 0) + weight);
const map = new Map<string, number>();
Interactive Tools for This Topic
FAQ
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. Its state lives in module-level bindings: `table`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.