Skip to content

Commit

Permalink
fix(number): bigint shouldn't throw when max is negative
Browse files Browse the repository at this point in the history
  • Loading branch information
soc221b committed Jan 3, 2025
1 parent bdd55ad commit 66b002b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/modules/number/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ export class NumberModule extends SimpleModuleBase {
* The bounds are inclusive.
*
* @param options Maximum value or options object.
* @param options.min Lower bound for generated bigint. Defaults to `0n`.
* @param options.min Lower bound for generated bigint. Defaults to `0n` or `max - 999999999999999n` if `max` is negative.
* @param options.max Upper bound for generated bigint. Defaults to `min + 999999999999999n`.
*
* @throws When `min` is greater than `max`.
Expand All @@ -397,7 +397,7 @@ export class NumberModule extends SimpleModuleBase {
/**
* Lower bound for generated bigint.
*
* @default 0n
* @default 0n or max - 999999999999999n if max is negative.
*/
min?: bigint | number | string | boolean;
/**
Expand All @@ -419,7 +419,12 @@ export class NumberModule extends SimpleModuleBase {
};
}

const min = BigInt(options.min ?? 0);
const min =
options.min === undefined
? 0n <= BigInt(options.max ?? 0n + BigInt(999999999999999))
? 0n
: BigInt(options.max ?? -999999999999999)
: BigInt(options.min);
const max = BigInt(options.max ?? min + BigInt(999999999999999));

if (max === min) {
Expand Down
4 changes: 4 additions & 0 deletions test/modules/number.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,10 @@ describe('number', () => {
expect(faker.number.bigInt({ max: 0n })).toBe(0n);
});

it('should return a random bigint given a maximum value of -1', () => {
expect(faker.number.bigInt({ max: -1n })).toBeLessThanOrEqual(-1n);
});

it('should return a random bigint given a negative bigint minimum and maximum value of 0', () => {
const generateBigInt = faker.number.bigInt({ min: -100n, max: 0n });
expect(generateBigInt).toBeGreaterThanOrEqual(-100n);
Expand Down

0 comments on commit 66b002b

Please sign in to comment.