mirror of
https://github.com/Horizontal42/summarum.git
synced 2026-11-10 15:42:01 +03:00
reject duplicate ids in addUnit
addUnit() overwrote unitsById unconditionally while its own addPhrase calls are first-wins, so an extension reusing an existing id silently corrupted the id->Unit table for anything using that id as a baseUnitId afterwards. Throw instead.
This commit is contained in:
parent
3b22d02bf3
commit
573b06e245
2 changed files with 8 additions and 0 deletions
|
|
@ -335,6 +335,13 @@ describe("extension API", () => {
|
|||
eng.addUnit({ id: "horse", phrases: "horse, horses, hrs", baseUnitId: "meter", format: "hrs", ratio: 2.4 });
|
||||
expect(calc("2 horses in meters")).toBe("4.8 m");
|
||||
});
|
||||
it("addUnit throws on id collision instead of silently corrupting unitsById", () => {
|
||||
expect(() =>
|
||||
eng.addUnit({ id: "horse", phrases: "nag", baseUnitId: "meter", format: "nag", ratio: 99 })
|
||||
).toThrow(/horse/);
|
||||
// the original registration must survive the failed collision
|
||||
expect(calc("2 horses in meters")).toBe("4.8 m");
|
||||
});
|
||||
it("addFunction (zum from Sample.js)", () => {
|
||||
eng.addFunction({ id: "zum", phrases: "zum" }, (values) => ({ double: values[0].double + values[1].double }));
|
||||
expect(calc("zum(2;3)")).toBe("5");
|
||||
|
|
|
|||
|
|
@ -218,6 +218,7 @@ export class SumEngine {
|
|||
addUnit(spec: ExtensionUnitSpec): void {
|
||||
const base = this.reg.unitsById.get(spec.baseUnitId) ?? this.currencyBase(spec.baseUnitId);
|
||||
if (!base) throw new Error(`numi.addUnit: unknown baseUnitId ${spec.baseUnitId}`);
|
||||
if (this.reg.unitsById.has(spec.id)) throw new Error(`numi.addUnit: id "${spec.id}" is already registered`);
|
||||
const unit: Unit = {
|
||||
id: spec.id,
|
||||
dimension: base.dimension,
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue