From f90c009d2888eb45f74637ec2b671ae5d7cd8f11 Mon Sep 17 00:00:00 2001 From: Braden MacDonald Date: Tue, 11 Oct 2022 14:14:31 -0700 Subject: [PATCH] fix: "remember" to use dimensionless units like "%" if originally used --- quantity.ts | 15 ++++++++++++++- tests/quantity.test.ts | 12 ++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/quantity.ts b/quantity.ts index f2ef490..a0a04b9 100644 --- a/quantity.ts +++ b/quantity.ts @@ -155,7 +155,7 @@ export class Quantity { } r += "±" + plusMinusString; } - if (!this.isDimensionless) { + if (serialized.units.length > 0) { r += " " + serialized.units; } return r; @@ -280,6 +280,19 @@ export class Quantity { remainder = bestRemainder; } + // Special case to handle dimensionless units like "%" that we may actually want to use: + if (unitList.length === 1 && useUnits.length === 0) { + // We want "50 % ⋅ 50 %" to give "25 %" + // But we want "50 % ⋅ 400 g" to give "200 g" (not "20,000 g⋅%"!) + for (let unitIdx = 0; unitIdx < unitList.length; unitIdx++) { + if (unitArray[unitIdx].isDimensionless) { + useUnits.push(unitIdx); + useUnitsPower.push(1); + break; // Only include up to one dimensionless unit like "%" + } + } + } + // At this point the units to be used are in useUnits return useUnits.map((i, pi) => ({ unit: unitList[i].unit, diff --git a/tests/quantity.test.ts b/tests/quantity.test.ts index d04933a..fb7616e 100644 --- a/tests/quantity.test.ts +++ b/tests/quantity.test.ts @@ -262,6 +262,18 @@ Deno.test("Multiplying quantities", async (t) => { assertEquals(z.magnitude, 15); assertEquals(z.dimensions, TWO_LENGTH_DIMENSIONS); // m² }); + await t.step(`(50 %) * (50 %)`, () => { + const x = new Quantity(50, { units: "%" }); + const y = new Quantity(50, { units: "%" }); + const z = x.multiply(y); + assertEquals(z.toString(), "25 %"); + }); + await t.step(`(50 %) * (400 g)`, () => { + const x = new Quantity(50, { units: "%" }); + const y = new Quantity(400, { units: "g" }); + const z = x.multiply(y); + assertEquals(z.toString(), "200 g"); + }); await t.step(`(500 g) * (2 m/s^2)`, () => { const x = new Quantity(500, { units: "g" }); const y = new Quantity(2, { units: "m/s^2" });