diff --git a/src/common/utils.ts b/src/common/utils.ts index 5d5681e10..c356355af 100644 --- a/src/common/utils.ts +++ b/src/common/utils.ts @@ -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; + 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); @@ -45,8 +69,19 @@ export const appendSIUnitToPhysicalQuantity = (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,