From 26df18f5e5e56c17fb8e570718f30cc26a55d168 Mon Sep 17 00:00:00 2001 From: Chris Duncan Date: Fri, 8 Aug 2025 08:24:31 -0700 Subject: [PATCH] Add number primitive support for unit conversion. --- src/lib/tools.ts | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/src/lib/tools.ts b/src/lib/tools.ts index 4f66a7b..a239994 100644 --- a/src/lib/tools.ts +++ b/src/lib/tools.ts @@ -21,13 +21,14 @@ type SweepResult = { /** * Converts a decimal amount of nano from one unit divider to another. * -* @param {(bigint|string)} amount - Decimal amount to convert +* @param {(bigint|number|string)} amount - Decimal amount to convert * @param {string} inputUnit - Current denomination * @param {string} outputUnit - Desired denomination */ -export async function convert (amount: bigint | string, inputUnit: string, outputUnit: string): Promise -export async function convert (amount: unknown, inputUnit: unknown, outputUnit: unknown): Promise { - if (typeof amount !== 'bigint' && typeof amount !== 'string') { +export function convert (amount: bigint | number | string, inputUnit: string, outputUnit: string): string +export function convert (amount: bigint | number | string, inputUnit: string, outputUnit: string, format?: 'bigint' | 'string'): bigint +export function convert (amount: unknown, inputUnit: unknown, outputUnit: unknown, format?: unknown): bigint | string { + if (typeof amount !== 'bigint' && typeof amount !== 'number' && typeof amount !== 'string') { throw new Error('Invalid amount', { cause: typeof amount }) } if (typeof amount === 'string' && !/^[0-9]+\.?[0-9]*$/.test(amount)) { @@ -46,12 +47,9 @@ export async function convert (amount: unknown, inputUnit: unknown, outputUnit: throw new Error(`Unknown denomination ${outputUnit}, expected one of the following: ${Object.keys(UNITS)}`) } - let i = '0', f = '0' - if (typeof amount === 'bigint') { - i = amount.toString() - } else { - [i, f] = amount.split('.') - } + let [i, f] = typeof amount === 'string' + ? amount.split('.') + : amount.toString().split('.') // convert to raw const inUnit = UNITS[inputUnit.toUpperCase()] @@ -73,10 +71,13 @@ export async function convert (amount: unknown, inputUnit: unknown, outputUnit: if (int < 1n) { throw new Error('Amount must be at least 1 raw') } - i = int.toString().padStart(40, '0') + if (format === 'bigint') { + return int + } // convert to desired denomination const outUnit = UNITS[outputUnit.toUpperCase()] + i = int.toString().padStart(40, '0') f = i.slice(40 - outUnit).replace(/0*$/g, '') i = i.slice(0, 40 - outUnit).replace(/^0*/g, '') -- 2.47.3