Skip to content

Commit

Permalink
fix: bigIntLikeToBigInt coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
jeeanribeiro committed Jun 8, 2024
1 parent 4789d91 commit 98509bd
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
22 changes: 19 additions & 3 deletions packages/shared/src/lib/core/utils/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,12 +273,28 @@ export class Converter {
* @returns The bytes.
*/
public static bigIntLikeToBigInt(number: BigIntLike | undefined): bigint {
if (number === undefined || number === null || Number.isNaN(number)) {
return BigInt(0)
}

if (ArrayBuffer.isView(number)) {
return bytesToBigInt(number)
} else {
number = number === '0x' ? '0x0' : number
return BigInt(String(number ?? '0'))
}

if (typeof number === 'string') {
if (number === '0x') {
return BigInt('0x0')
}
if (/\d+\.?\d*e[+-]?\d+/i.test(number)) {
number = Number(number)
}
}

if (typeof number === 'number' && !Number.isInteger(number)) {
number = Math.floor(number)
}

return BigInt(number)
}

/**
Expand Down
23 changes: 23 additions & 0 deletions packages/shared/src/lib/core/utils/tests/convert.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,30 @@ describe('File: convert.ts', () => {
expect(Converter.bigIntLikeToBigInt('0')).toEqual(BigInt(0))
expect(Converter.bigIntLikeToBigInt(100)).toEqual(BigInt(100))
expect(Converter.bigIntLikeToBigInt('123330')).toEqual(BigInt(123330))
})
it('should handle floats by truncating', () => {
expect(Converter.bigIntLikeToBigInt(123.456)).toEqual(BigInt(123))
})
it('should handle scientific notation', () => {
expect(Converter.bigIntLikeToBigInt('1e6')).toEqual(BigInt(1000000))
expect(Converter.bigIntLikeToBigInt('1.23e3')).toEqual(BigInt(1230))
expect(Converter.bigIntLikeToBigInt('-1e6')).toEqual(BigInt(-1000000))
expect(Converter.bigIntLikeToBigInt('1.23e-3')).toEqual(BigInt(0))
})
it('should handle string representations of numbers', () => {
expect(Converter.bigIntLikeToBigInt('123456789012345678901234567890')).toEqual(
BigInt('123456789012345678901234567890')
)
expect(Converter.bigIntLikeToBigInt('-123456789012345678901234567890')).toEqual(
BigInt('-123456789012345678901234567890')
)
})
it('should handle edge cases', () => {
expect(Converter.bigIntLikeToBigInt('')).toEqual(BigInt(0))
expect(Converter.bigIntLikeToBigInt(undefined)).toEqual(BigInt(0))
expect(Converter.bigIntLikeToBigInt(null)).toEqual(BigInt(0))
expect(Converter.bigIntLikeToBigInt(NaN)).toEqual(BigInt(0))
expect(Converter.bigIntLikeToBigInt(false)).toEqual(BigInt(0))
})
})
})

0 comments on commit 98509bd

Please sign in to comment.