From f4dedf790ed001ee3b8bf8eb0b716aaa19b088cd Mon Sep 17 00:00:00 2001 From: Leon Radley Date: Tue, 30 May 2023 15:18:17 +0200 Subject: [PATCH] feat(number): support step on faker.number.int() Fixes #2186 --- src/modules/number/index.ts | 16 ++++++++++++++-- test/number.spec.ts | 16 ++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/modules/number/index.ts b/src/modules/number/index.ts index fce3829a72e..ad2d4ede545 100644 --- a/src/modules/number/index.ts +++ b/src/modules/number/index.ts @@ -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); @@ -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; } /** diff --git a/test/number.spec.ts b/test/number.spec.ts index c0bdf609de6..086af358552 100644 --- a/test/number.spec.ts +++ b/test/number.spec.ts @@ -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', () => {