Skip to content

Commit

Permalink
feat(number): support step on faker.number.int()
Browse files Browse the repository at this point in the history
  • Loading branch information
Leon Radley committed May 30, 2023
1 parent 27a8ff7 commit f4dedf7
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/modules/number/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,19 @@ export class NumberModule {
* @default Number.MAX_SAFE_INTEGER
*/
max?: number;
/**
* Increment value for generated number.
*
* @default 1
*/
step?: number;
} = {}
): number {
if (typeof options === 'number') {
options = { max: options };
}

const { min = 0, max = Number.MAX_SAFE_INTEGER } = options;
const { min = 0, max = Number.MAX_SAFE_INTEGER, step = 1 } = options;
const effectiveMin = Math.ceil(min);
const effectiveMax = Math.floor(max);

Expand All @@ -91,11 +97,17 @@ export class NumberModule {
throw new FakerError(`Max ${max} should be greater than min ${min}.`);
}

if (step <= 0) {
throw new FakerError(`Step should be a positive number.`);
}

const mersenne: Mersenne =
// @ts-expect-error: access private member field
this.faker._mersenne;
const real = mersenne.next();
return Math.floor(real * (effectiveMax + 1 - effectiveMin) + effectiveMin);
const range = (effectiveMax - effectiveMin) / step;
const rand = Math.floor(real * (range + 1));
return effectiveMin + rand * step;
}

/**
Expand Down
16 changes: 16 additions & 0 deletions test/number.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,22 @@ describe('number', () => {
new FakerError(`No integer value between 2.1 and 2.9 found.`)
);
});

it('should return a random number between min max, with a step size of 10', () => {
const results = Array.from(
new Set(
Array.from({ length: 50 }, () =>
faker.number.int({
min: 0,
max: 50,
step: 10,
})
)
)
).sort();

expect(results).toEqual([0, 10, 20, 30, 40, 50]);
});
});

describe('float', () => {
Expand Down

0 comments on commit f4dedf7

Please sign in to comment.