From: Chris Duncan Date: Mon, 3 Aug 2026 18:50:08 +0000 (-0700) Subject: Fix unit conversion to work with readonly unit object. X-Git-Url: https://git.codecow.com/?a=commitdiff_plain;h=b5765f2bb952540c6a49ab52974210661452b2ad;p=libnemo.git Fix unit conversion to work with readonly unit object. --- diff --git a/src/lib/tools.ts b/src/lib/tools.ts index 9c8e28e..b3e4b5b 100644 --- a/src/lib/tools.ts +++ b/src/lib/tools.ts @@ -37,22 +37,19 @@ export function convert (amount: unknown, inputUnit: unknown, outputUnit: unknow if (typeof inputUnit !== 'string') { throw new TypeError('Invalid input unit', { cause: typeof inputUnit }) } - (inputUnit as string) = inputUnit.toUpperCase() if (typeof outputUnit !== 'string') { throw new TypeError('Invalid output unit', { cause: typeof outputUnit }) } - (outputUnit as string) = outputUnit.toUpperCase() - if (UNITS[inputUnit] == null) { - throw new Error(`Unknown denomination ${inputUnit}, expected one of the following: ${Object.keys(UNITS)}`) - } - if (UNITS[outputUnit] == null) { - throw new Error(`Unknown denomination ${outputUnit}, expected one of the following: ${Object.keys(UNITS)}`) - } if (format !== undefined && format !== 'bigint' && format !== 'number' && format !== 'string') { throw new Error('Invalid output format', { cause: format }) } + inputUnit = inputUnit.toUpperCase() + outputUnit = outputUnit.toUpperCase() - const inUnit = UNITS[inputUnit] + const inUnit = UNITS[inputUnit as keyof typeof UNITS] + if (inUnit == null) { + throw new Error(`Unknown denomination ${inputUnit}, expected one of the following: ${Object.keys(UNITS)}`) + } let [i, f] = typeof amount === 'string' ? amount.split('.') : dec.toString(amount).split('.') @@ -79,7 +76,10 @@ export function convert (amount: unknown, inputUnit: unknown, outputUnit: unknow } // convert to desired denomination - const outUnit = UNITS[outputUnit] + const outUnit = UNITS[outputUnit as keyof typeof UNITS] + if (outUnit == null) { + throw new Error(`Unknown denomination ${outputUnit}, expected one of the following: ${Object.keys(UNITS)}`) + } i = dec.toString(int, 40) f = i.slice(40 - outUnit).replace(/0*$/g, '') i = i.slice(0, 40 - outUnit).replace(/^0*/g, '')