Skip to content

Commit

Permalink
fix: "remember" to use dimensionless units like "%" if originally used
Browse files Browse the repository at this point in the history
  • Loading branch information
bradenmacdonald committed Oct 11, 2022
1 parent 0b60778 commit f90c009
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
15 changes: 14 additions & 1 deletion quantity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ export class Quantity {
}
r += "±" + plusMinusString;
}
if (!this.isDimensionless) {
if (serialized.units.length > 0) {
r += " " + serialized.units;
}
return r;
Expand Down Expand Up @@ -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,
Expand Down
12 changes: 12 additions & 0 deletions tests/quantity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" });
Expand Down

0 comments on commit f90c009

Please sign in to comment.