]> git.codecow.com Git - nano-pow.git/commitdiff
Simplify string to bigint conversion.
authorChris Duncan <chris@codecow.com>
Mon, 22 Jun 2026 15:52:38 +0000 (08:52 -0700)
committerChris Duncan <chris@codecow.com>
Mon, 22 Jun 2026 15:52:38 +0000 (08:52 -0700)
src/utils/bigint.ts

index ab5a0b3a11372b0fd0645d146674de86ec662a21..d3f9b2e99c8dbc03000c8c26ec7be4506f25328d 100644 (file)
@@ -24,30 +24,21 @@ export function bigintToU64 (int: bigint, length: number): BigUint64Array<ArrayB
        return u64
 }
 
-export function bigintFrom (value: bigint | boolean | number | string | unknown, type?: 'bin' | 'oct' | 'hex'): bigint {
-       if (typeof value === 'bigint') {
-               return value
-       } else if (typeof value === 'boolean' || typeof value === 'number') {
-               return BigInt(value)
-       } else if (typeof value === 'string') {
-               const v = value.trim().replace(/n$/, '')
-               if (/^0[Bb][01]+$/.test(v)
-                       || /^0[Oo][0-7]+$/.test(v)
-                       || /^0[Xx][A-Fa-f\d]+$/.test(v)
-                       || /^\d+$/.test(v)) {
-                       return BigInt(v)
+export function bigintFrom (value: bigint | boolean | number | string | unknown): bigint {
+       switch (typeof value) {
+               case 'bigint':
+               case 'boolean':
+               case 'number': {
+                       return BigInt(value)
                }
-               if (type === 'bin' && /^[01]+$/.test(v)) {
-                       return BigInt(`0b${v}`)
-               }
-               if (type === 'oct' && /^[0-7]+$/.test(v)) {
-                       return BigInt(`0o${v}`)
-               }
-               if (type === 'hex' || /^\d*[A-Fa-f]+\d*$/.test(v)) {
+               case 'string': {
+                       const v = value.trim().replace(/^0[Xx]/, '').replace(/n$/, '')
                        return BigInt(`0x${v}`)
                }
+               default: {
+                       throw new TypeError(`can't convert value to BigInt`)
+               }
        }
-       throw new TypeError(`can't convert string to BigInt`)
 }
 
 export function bigintToHex (int: bigint, length: unknown = 0): string {