import type { Units } from "../models/units" ; /**
 * Class to help with units formatting.
 */ export class UnitsHelper { /**
     * Map units.
     */ public static readonly UNIT_MAP : { [ unit in Units ] : { val : number ; dp : number ; } ; } = { i : { val : 1 , dp : 0 } , Ki : { val : 1000 , dp : 3 } , Mi : { val : 1000000 , dp : 6 } , Gi : { val : 1000000000 , dp : 9 } , Ti : { val : 1000000000000 , dp : 12 } , Pi : { val : 1000000000000000 , dp : 15 } } ; param value param decimalPlaces returns public static formatBest ( value , decimalPlaces = 2 ) { return UnitsHelper . formatUnits ( value , UnitsHelper . calculateBest ( value ) , decimalPlaces ) ; } param value param unit param decimalPlaces returns public static formatUnits ( value , unit , decimalPlaces = 2 ) { if ( ! UnitsHelper . UNIT_MAP [ unit ] ) { throw new Error ( `Unrecognized unit ${ unit }` ) ; } if ( ! value ) { return `0 ${ unit }` ; } return unit === "i" ? `${ value } i` : `${ UnitsHelper . convertUnits ( value , "i" , unit ) . toFixed ( decimalPlaces ) } ${ unit }` ; } param value returns public static calculateBest ( value ) { let bestUnits = "i" ; if ( ! value ) { return bestUnits ; } const checkLength = Math . abs ( value ) . toString ( ) . length ; if ( checkLength > UnitsHelper . UNIT_MAP . Pi . dp ) { bestUnits = "Pi" ; } else if ( checkLength > UnitsHelper . UNIT_MAP . Ti . dp ) { bestUnits = "Ti" ; } else if ( checkLength > UnitsHelper . UNIT_MAP . Gi . dp ) { bestUnits = "Gi" ; } else if ( checkLength > UnitsHelper . UNIT_MAP . Mi . dp ) { bestUnits = "Mi" ; } else if ( checkLength > UnitsHelper . UNIT_MAP . Ki . dp ) { bestUnits = "Ki" ; } return bestUnits ; } param value param fromUnit param toUnit returns public static convertUnits ( value , fromUnit , toUnit ) { if ( ! value ) { return 0 ; } if ( ! UnitsHelper . UNIT_MAP [ fromUnit ] ) { throw new Error ( `Unrecognized fromUnit ${ fromUnit }` ) ; } if ( ! UnitsHelper . UNIT_MAP [ toUnit ] ) { throw new Error ( `Unrecognized toUnit ${ toUnit }` ) ; } if ( fromUnit === "i" && value % 1 !== 0 ) { throw new Error ( "If fromUnit is 'i' the value must be an integer value" ) ; } if ( fromUnit === toUnit ) { return Number ( value ) ; } const multiplier = value < 0 ? - 1 : 1 ; const scaledValue = ( Math . abs ( Number ( value ) ) * UnitsHelper . UNIT_MAP [ fromUnit ] . val ) / UnitsHelper . UNIT_MAP [ toUnit ] . val ; const numDecimals = UnitsHelper . UNIT_MAP [ toUnit ] . dp ; let fixed = scaledValue . toString ( ) ; if ( fixed . includes ( "e" ) ) { fixed = scaledValue . toFixed ( Number . parseInt ( fixed . split ( "-" ) [ 1 ] , 10 ) ) ; } const parts = fixed . split ( "." ) ; if ( parts . length === 1 ) { parts . push ( "0" ) ; } parts [ 1 ] = parts [ 1 ] . slice ( 0 , numDecimals ) ; return Number . parseFloat ( `${ parts [ 0 ] }.${ parts [ 1 ] }` ) * multiplier ; } }