random
The random utility generates a pseudo-random integer between two specified values (inclusive). It simplifies common randomization tasks like picking a range, rolling dice, or generating random offsets.
Implementation
View Source Code
ts
import { assert } from '../function/assert';
/**
* Generates a random integer between two values, inclusive.
*
* @example
* ```ts
* random(1, 10); // a random integer between 1 and 10
* ```
*
* @param min - The minimum value.
* @param max - The maximum value.
* @returns A random integer between min and max.
*/
export function random(min: number, max: number): number {
assert(min <= max, 'Minimum value must be less than maximum value', { args: { max, min }, type: RangeError });
const randomValue = crypto ? crypto.getRandomValues(new Uint32Array(1))[0] / 0xffffffff : Math.random();
return Math.floor(randomValue * (max - min + 1)) + min;
}Features
- Isomorphic: Works in both Browser and Node.js.
- Inclusive Range: Includes both the minimum and maximum values in the potential output.
- Robust: Automatically handles cases where
minis greater thanmaxby swapping them. - Integer Output: Always returns a whole number.
API
ts
function random(min?: number, max?: number): number;Parameters
min: Optional. The lower bound of the range (defaults to0).max: Optional. The upper bound of the range (defaults to100).
Returns
- A random integer between
minandmax(inclusive).
Examples
Basic Usage
ts
import { random } from '@vielzeug/toolkit';
// Random number between 0 and 100
random();
// Random number between 1 and 10
random(1, 10);Die Roll Example
ts
import { random } from '@vielzeug/toolkit';
function rollDie() {
return random(1, 6);
}
console.log(`You rolled a ${rollDie()}`);Implementation Notes
- Performance-optimized using
Math.random(). - Swaps
minandmaxinternally ifmin > maxto prevent errors. - Uses
Math.floorto ensure integer results.