From f29e85c28b994aaf958702f3d3fddeb5ee2a4430 Mon Sep 17 00:00:00 2001 From: Willy Brauner Date: Tue, 17 Oct 2023 10:31:42 +0200 Subject: [PATCH] Fix randomRange --- src/index.ts | 1 + src/math/randomRange.ts | 8 ++++---- tests/math/randomRange.test.ts | 22 ++++++++++++++++++++-- 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/src/index.ts b/src/index.ts index d355bcb..57fd1b7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,6 +11,7 @@ export { clamp } from "./math/clamp" export { modulo } from "./math/modulo" export { normalizeValue } from "./math/normalizeValue" export { originalValueFromNormalized } from "./math/normalizeValue" +export { randomRange } from "./math/randomRange" // promise export { deferredPromise } from "./promise/deferredPromise" export type { TDeferredPromise } from "./promise/deferredPromise" diff --git a/src/math/randomRange.ts b/src/math/randomRange.ts index a5c24a8..0192b92 100644 --- a/src/math/randomRange.ts +++ b/src/math/randomRange.ts @@ -2,9 +2,9 @@ * Get random value between min and max (include) * @param min * @param max - * @param decimal + * @param decimalNumber 1 = 0.1, 2 = 0.01, 3 = 0.001 */ -export function randomRange(min: number, max: number, decimal = 0): number { - const power = Math.pow(10, decimal) - return Math.floor(Math.random() * (max - min + 1) + min * power) / power +export function randomRange(min: number, max: number, decimalNumber = 0): number { + if (decimalNumber < 0) return + return parseFloat((Math.random() * (max - min) + min).toFixed(decimalNumber)) } diff --git a/tests/math/randomRange.test.ts b/tests/math/randomRange.test.ts index 5cdfa22..71b5d02 100644 --- a/tests/math/randomRange.test.ts +++ b/tests/math/randomRange.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from "vitest" -import { randomRange } from "../../src/math/randomRange" - +import { randomRange } from "../../src" describe("randomRange", () => { it("should return random value between min and max", () => { @@ -15,4 +14,23 @@ describe("randomRange", () => { } } }) + + it("should generate a random integer within the specified range", () => { + const result = randomRange(1, 10) + expect(result).toBeTypeOf("number") + expect(result).toBeGreaterThanOrEqual(1) + expect(result).toBeLessThanOrEqual(10) + }) + + it("should generate a random float with the specified number of decimal places", () => { + const result = randomRange(1.5, 5.5, 2) + expect(result).toBeTypeOf("number") + expect(result).toBeGreaterThanOrEqual(1.5) + expect(result).toBeLessThanOrEqual(5.5) + expect(result.toFixed(2)).toBe(result.toString()) + }) + + it("should return undefined if there is no valid decimal set as param", () => { + expect(randomRange(0, 1, -1)).toBeUndefined() + }) })