From f278ff92946625f4c908e4158336171acec43c77 Mon Sep 17 00:00:00 2001 From: Refringe Date: Mon, 9 Dec 2024 20:21:06 -0500 Subject: [PATCH] Updates `RandomUtil.randInt` to handle floating-point parameters by flooring values. I hate this! --- project/src/utils/RandomUtil.ts | 24 ++++++++++++++++++++---- project/tests/utils/RandomUtil.test.ts | 5 +++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/project/src/utils/RandomUtil.ts b/project/src/utils/RandomUtil.ts index fd09c548..9196e25c 100644 --- a/project/src/utils/RandomUtil.ts +++ b/project/src/utils/RandomUtil.ts @@ -298,7 +298,7 @@ export class RandomUtil { /** * Returns a random string from the provided array of strings. * - * This method is separate from getArrayValue so we can use a generic inferance with getArrayValue. + * This method is separate from getArrayValue so we can use a generic inference with getArrayValue. * * @param arr - The array of strings to select a random value from. * @returns A randomly selected string from the array. @@ -383,22 +383,38 @@ export class RandomUtil { /** * Generates a random integer between the specified range. + * Low and high parameters are floored to integers. + * + * TODO: v3.11 - This method should not accept non-integer numbers. * * @param low - The lower bound of the range (inclusive). * @param high - The upper bound of the range (exclusive). If not provided, the range will be from 0 to `low`. * @returns A random integer within the specified range. */ public randInt(low: number, high?: number): number { + let randomLow = low; + let randomHigh = high; + + // Detect if either of the parameters is a float, and log a warning + if (low % 1 !== 0 || (typeof high !== "undefined" && high % 1 !== 0)) { + // Round the float values to the nearest integer. Eww! + randomLow = Math.floor(low); + if (typeof high !== "undefined") { + randomHigh = Math.floor(high); + } + } + + // Return a random integer from 0 to low if high is not provided if (typeof high === "undefined") { - return crypto.randomInt(0, low); + return crypto.randomInt(0, randomLow); } // Return low directly when low and high are equal if (low === high) { - return low; + return randomLow; } - return crypto.randomInt(low, high); + return crypto.randomInt(randomLow, randomHigh); } /** diff --git a/project/tests/utils/RandomUtil.test.ts b/project/tests/utils/RandomUtil.test.ts index 44ab463b..a3164f2d 100644 --- a/project/tests/utils/RandomUtil.test.ts +++ b/project/tests/utils/RandomUtil.test.ts @@ -399,6 +399,11 @@ describe("RandomUtil", () => { expect(result).toBe(5); }); + it("should work with float number parameters", () => { + const result = randomUtil.randInt(5.5, 10.5); + expect(result).toBeGreaterThanOrEqual(5); + expect(result).toBeLessThan(11); + }); it("should return an integer between low and high - 1", () => { const low = 5; const high = 10;