Skip to content

Commit

Permalink
Unitless quantity conversion bug (#3117)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>
  • Loading branch information
costerwi and josdejong authored Jan 10, 2024
1 parent af55b12 commit f89e3cb
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/type/unit/Unit.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down
3 changes: 3 additions & 0 deletions test/unit-tests/function/arithmetic/abs.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand Down
1 change: 1 addition & 0 deletions test/unit-tests/type/unit/Unit.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand Down

0 comments on commit f89e3cb

Please sign in to comment.