Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix randomRange #17

Merged
merged 1 commit into from
Oct 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
8 changes: 4 additions & 4 deletions src/math/randomRange.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
22 changes: 20 additions & 2 deletions tests/math/randomRange.test.ts
Original file line number Diff line number Diff line change
@@ -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", () => {
Expand All @@ -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()
})
})
Loading