]> git.codecow.com Git - libnemo.git/commitdiff
Fix unit conversion to work with readonly unit object.
authorChris Duncan <chris@codecow.com>
Mon, 3 Aug 2026 18:50:08 +0000 (11:50 -0700)
committerChris Duncan <chris@codecow.com>
Mon, 3 Aug 2026 18:50:08 +0000 (11:50 -0700)
src/lib/tools.ts

index 9c8e28e283cad6c5a98beededcb87abd3274f7d1..b3e4b5bd4cc4ea06b4e2cb38dcab9bdfe99d7f27 100644 (file)
@@ -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, '')