multiplying same-dimension quantities keeps a sane unit

"2 kg * 500 g" multiplied the raw numbers (1000) and slapped the
left unit on top, giving "1000 kg" instead of "1 kg". Convert the
right operand into the left unit first for same-dimension products;
cross-dimension multiplication ($12 * 3, 5 hours * 2) is unaffected.
This commit is contained in:
Horizontal42 2026-07-03 11:25:01 +03:00
parent df7761401b
commit deea37ba21
2 changed files with 7 additions and 0 deletions

View file

@ -219,4 +219,9 @@ describe("review fixes", () => {
it("random() participates in arithmetic", () => {
expect(calc("random() + 1")).not.toBeNull();
});
it("multiplying same-dimension quantities converts the right operand", () => {
expect(calc("2 kg * 500 g")).toBe("1 kg");
expect(calc("$12 * 3")).toBe("$36");
expect(calc("2 m * 3 m")).toBe("6 m²");
});
});

View file

@ -252,6 +252,8 @@ function evalBin(op: "plus" | "minus" | "mul" | "div" | "mod" | "pow", l: Value,
const u = ctx.reg.unitsById.get(targetId);
if (u) return qty(baseProduct.div(u.ratio), u);
}
// same dimension: "2 kg * 500 g" scales in the left unit, not 2*500
if (da === db) return qty(a.value.mul(convertQ(b, a.unit).value), a.unit);
return qty(a.value.mul(b.value), a.unit);
}
return qty(a.value.mul(b.value), a.unit ?? b.unit ?? null);