Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(number): bigint shouldn't throw when max is negative #3363

Open
wants to merge 2 commits into
base: next
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading