Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 38 additions & 3 deletions src/common/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,36 @@ import {
} from "./interfaces/common.interface";
import { ScientificRelation } from "./scientific-relation.enum";

export const convertArrayToSI = (
inputValue: number[],
inputUnit: string,
): { valueSI: number[]; unitSI: string } => {
try {
const newUnit = unit(inputUnit).toSI().toJSON().unit;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can add a comment for this workaround, so that we can easier find to roll back these changes once upstream mathjs has fixed that behaviour ( and if possible reference a mathjs bug report as well)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#1005 bumped to version with fixed mathjs (see https://github.com/josdejong/mathjs/blob/develop/HISTORY.md#2024-01-12-1230) so we could drop the workaround now.

if (inputValue && inputValue.length) {
const value = Array.from(
inputValue,
(iValue) => unit(iValue, inputUnit).to(newUnit).toJSON().value,
);
return { valueSI: value, unitSI: newUnit };
} else {
return { valueSI: inputValue, unitSI: newUnit };
}
} catch (error) {
console.error(error);
return { valueSI: inputValue, unitSI: inputUnit };
}
};

export const convertToSI = (
inputValue: number,
inputUnit: string,
): { valueSI: number; unitSI: string } => {
try {
const quantity = unit(inputValue, inputUnit).toSI().toJSON();
// Workaround related to a bug reported at https://github.com/josdejong/mathjs/issues/3097 and https://github.com/josdejong/mathjs/issues/2499
const quantity = unit(inputValue, inputUnit)
.to(unit(inputUnit).toSI().toJSON().unit)
.toJSON();
return { valueSI: Number(quantity.value), unitSI: quantity.unit };
} catch (error) {
console.error(error);
Expand Down Expand Up @@ -45,8 +69,19 @@ export const appendSIUnitToPhysicalQuantity = <T extends object>(object: T) => {
] as unknown as number;
}
});

if (value !== undefined && unit && unit.length > 0) {
if (
value !== undefined &&
Array.isArray(value) &&
unit &&
unit.length > 0
) {
const { valueSI, unitSI } = convertArrayToSI(value, unit);
updatedObject[key as keyof T] = {
...instance,
valueSI,
unitSI,
};
} else if (value !== undefined && unit && unit.length > 0) {
const { valueSI, unitSI } = convertToSI(value, unit);
updatedObject[key as keyof T] = {
...instance,
Expand Down