randomInRange
Returns a random integer between min and max (inclusive).
1/**
2 * Returns a random integer between min and max (inclusive).
3 *
4 * @param min - The minimum value.
5 * @param max - The maximum value.
6 * @returns A random integer within the specified range.
7 * @throws If min is greater than max.
8 */
9export function randomInRange(min: number, max: number): number {
10 if (min > max) {
11 throw new Error('"min" should not be greater than "max"');
12 }
13 return Math.floor(Math.random() * (max - min + 1)) + min;
14}
Inclusive Range Support
Ensures both
min
andmax
values can be returned, which is often expected in random integer generation.Input Validation
Throws an explicit error if
min
is greater thanmax
, preventing silent logic bugs.Compact and Efficient
Uses a straightforward and performant formula with minimal overhead.
Pure Utility Function
Stateless and self-contained, making it safe to reuse and easy to test (with mocking if needed).
Tests | Examples
1test('randomInRange - returns value within inclusive range', () => {
2 for (let i = 0; i < 100; i++) {
3 const val = randomInRange(5, 10);
4 expect(val).toBeGreaterThanOrEqual(5);
5 expect(val).toBeLessThanOrEqual(10);
6 }
7});
8
9test('randomInRange - single value range returns that value', () => {
10 expect(randomInRange(7, 7)).toBe(7);
11});
12
13test('randomInRange - throws if min > max', () => {
14 expect(() => randomInRange(10, 5)).toThrow('"min" should not be greater than "max"');
15});
Common Use Cases
Randomized Testing
Generate test inputs or simulate edge cases with values in a defined range.
Game Mechanics
Roll dice, determine damage, pick random spawn points, or simulate luck-based logic.
Sampling and Simulation
Select random numeric values for simulations, models, or probabilistic algorithms.
UI Randomization
Add variability to animations, delays, or layout arrangements for visual effects.
Lottery or Prize Draw Systems
Pick a random winner or generate IDs/numbers within defined bounds.