Skip to content

Commit

Permalink
Handling 0 as a divisor in BigInt divide util (#3374)
Browse files Browse the repository at this point in the history
  • Loading branch information
manojVivek authored Jun 28, 2023
1 parent 111bd14 commit 5169cc7
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
12 changes: 12 additions & 0 deletions ui/packages/shared/utilities/src/bigint.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,15 @@ describe('lowestNumberWithSameNumberOfDigits', () => {
expect(lowestNumberWithSameNumberOfDigits(9007199254740991)).toBe(1000000000000000);
});
});

describe('divide', () => {
it('divides two bigints and returns a number', () => {
expect(divide(4n, 2n)).toBe(2);
});
it('divides two bigints and returns a number with decimals if available', () => {
expect(divide(5n, 2n)).toBe(2.5);
});
it('handles divide by zero', () => {
expect(divide(5n, 0n)).toBe(Infinity);
});
});
3 changes: 3 additions & 0 deletions ui/packages/shared/utilities/src/bigint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ const MULTIPLE = lowestNumberWithSameNumberOfDigits(Number.MAX_SAFE_INTEGER);
const MULTIPLE_BIGINT = BigInt(MULTIPLE);

export const divide = (a: bigint, b: bigint): number => {
if (b === 0n) {
return Infinity;
}
return Number((a * MULTIPLE_BIGINT) / b) / MULTIPLE;
};

Expand Down

0 comments on commit 5169cc7

Please sign in to comment.