From: Jérôme Benoit Date: Fri, 10 Feb 2023 10:30:43 +0000 (+0100) Subject: refactor(simulator): random float generator signature simplification X-Git-Tag: v1.1.93~3 X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=2f45578b9925ac9137d92898216c8c4c0b0bacdc;p=e-mobility-charging-stations-simulator.git refactor(simulator): random float generator signature simplification Signed-off-by: Jérôme Benoit --- diff --git a/src/utils/Utils.ts b/src/utils/Utils.ts index 34ace09c..ab2a8a5f 100644 --- a/src/utils/Utils.ts +++ b/src/utils/Utils.ts @@ -121,13 +121,15 @@ export default class Utils { return result; } - public static getRandomFloat(max = Number.MAX_VALUE, min = 0, negative = false): number { - if (max < min || max < 0 || min < 0) { + public static getRandomFloat(max = Number.MAX_VALUE, min = 0): number { + if (max < min) { + throw new RangeError('Invalid interval'); + } + if (max - min === Infinity) { throw new RangeError('Invalid interval'); } const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff; - const sign = negative && randomPositiveFloat < 0.5 ? -1 : 1; - return sign * (randomPositiveFloat * (max - min) + min); + return randomPositiveFloat * (max - min) + min; } public static getRandomInteger(max = Constants.MAX_RANDOM_INTEGER, min = 0): number { diff --git a/test/utils/UtilsTest.ts b/test/utils/UtilsTest.ts index 9d694308..423d61f3 100644 --- a/test/utils/UtilsTest.ts +++ b/test/utils/UtilsTest.ts @@ -110,6 +110,9 @@ describe('Utils test suite', () => { expect(randomInteger).toBeGreaterThanOrEqual(0); expect(randomInteger).toBeLessThanOrEqual(Constants.MAX_RANDOM_INTEGER); expect(randomInteger).not.toEqual(Utils.getRandomInteger()); + randomInteger = Utils.getRandomInteger(0, -Constants.MAX_RANDOM_INTEGER); + expect(randomInteger).toBeGreaterThanOrEqual(-Constants.MAX_RANDOM_INTEGER); + expect(randomInteger).toBeLessThanOrEqual(0); expect(() => Utils.getRandomInteger(0, 1)).toThrowError( 'The value of "max" is out of range. It must be greater than the value of "min" (1). Received 1' ); @@ -138,11 +141,12 @@ describe('Utils test suite', () => { expect(randomFloat).toBeLessThanOrEqual(Number.MAX_VALUE); expect(randomFloat).not.toEqual(Utils.getRandomFloat()); expect(() => Utils.getRandomFloat(0, 1)).toThrowError(new RangeError('Invalid interval')); - expect(() => Utils.getRandomFloat(-1)).toThrowError(new RangeError('Invalid interval')); - expect(() => Utils.getRandomFloat(0, -1)).toThrowError(new RangeError('Invalid interval')); - randomFloat = Utils.getRandomFloat(Number.MAX_VALUE, 0, true); + expect(() => Utils.getRandomFloat(Number.MAX_VALUE, -Number.MAX_VALUE)).toThrowError( + new RangeError('Invalid interval') + ); + randomFloat = Utils.getRandomFloat(0, -Number.MAX_VALUE); expect(randomFloat).toBeGreaterThanOrEqual(-Number.MAX_VALUE); - expect(randomFloat).toBeLessThanOrEqual(Number.MAX_VALUE); + expect(randomFloat).toBeLessThanOrEqual(0); }); it('Verify isIterable()', () => {