From f89e3cbbff4962378bbd8f6024201a43cff2662b Mon Sep 17 00:00:00 2001 From: Carl Osterwisch Date: Wed, 10 Jan 2024 11:53:18 -0500 Subject: [PATCH] Unitless quantity conversion bug (#3117) * Add test for conversion to unitless quantity * Avoid access to missing array index * Also check that other.units is not empty * Add test for abs of dimensionless unit * Fix: avoid access to missing units array index --------- Co-authored-by: Jos de Jong --- src/type/unit/Unit.js | 3 ++- test/unit-tests/function/arithmetic/abs.test.js | 3 +++ test/unit-tests/type/unit/Unit.test.js | 1 + 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/type/unit/Unit.js b/src/type/unit/Unit.js index 0ae5c59818..c9d2e2ad14 100644 --- a/src/type/unit/Unit.js +++ b/src/type/unit/Unit.js @@ -780,7 +780,7 @@ export const createUnitClass = /* #__PURE__ */ factory(name, dependencies, ({ Unit.prototype.abs = function () { const ret = this.clone() if (ret.value !== null) { - if (ret._isDerived() || ret.units[0].unit.offset === 0) { + if (ret._isDerived() || ret.units.length === 0 || ret.units[0].unit.offset === 0) { ret.value = abs(ret.value) } else { // To give the correct, but unexpected, results for units with an offset. @@ -828,6 +828,7 @@ export const createUnitClass = /* #__PURE__ */ factory(name, dependencies, ({ } if (this.value === null || this._isDerived() || + this.units.length === 0 || other.units.length === 0 || this.units[0].unit.offset === other.units[0].unit.offset) { other.value = clone(value) } else { diff --git a/test/unit-tests/function/arithmetic/abs.test.js b/test/unit-tests/function/arithmetic/abs.test.js index a737ba37e9..f1392927e9 100644 --- a/test/unit-tests/function/arithmetic/abs.test.js +++ b/test/unit-tests/function/arithmetic/abs.test.js @@ -84,6 +84,9 @@ describe('abs', function () { u = abs(unit(complex(-4, 3), 'in')) assert.strictEqual(u.toString(), '5 in') + + u = abs(unit(-10)) // dimensionless unit + assert.strictEqual(u.toString(), '10') }) it('should throw an error in case of invalid number of arguments', function () { diff --git a/test/unit-tests/type/unit/Unit.test.js b/test/unit-tests/type/unit/Unit.test.js index 14af3530ea..96cd666191 100644 --- a/test/unit-tests/type/unit/Unit.test.js +++ b/test/unit-tests/type/unit/Unit.test.js @@ -393,6 +393,7 @@ describe('Unit', function () { it('should convert a unitless quantity', function () { const u = Unit.parse('5', { allowNoUnits: true }) assert.strictEqual(u.toNumeric(), 5) + assert.strictEqual(u.toNumeric('mm/m'), 5000) }) it('should convert a binary prefixes (1)', function () {