random
Generate random numbers within a specified range.
Basic Usage
typescript
import { random } from 'radash'
console.log(random(1, 10)) // Generate a random integer between 1 and 10
console.log(random(0, 1)) // Generate a random floating-point number between 0 and 1
console.log(random(10, 20, true)) // Generate a random integer between 10 and 20
Syntax
typescript
function random(
min: number,
max: number,
inclusive?: boolean
): number
Parameters
min
(number): Minimum valuemax
(number): Maximum valueinclusive
(boolean, optional): Whether to include the maximum value, default is false
Return Value
Returns a random number within the specified range.
Examples
Generate Integers
typescript
import { random } from 'radash'
console.log(random(1, 10)) // Random integer between 1 and 9
console.log(random(1, 10, true)) // Random integer between 1 and 10
console.log(random(0, 100)) // Random integer between 0 and 99
console.log(random(-10, 10)) // Random integer between -10 and 9
Generate Floating-Point Numbers
typescript
import { random } from 'radash'
console.log(random(0, 1)) // Random float between 0 and 1
console.log(random(0, 1, true)) // Random float between 0 and 1 (inclusive)
console.log(random(1.5, 2.5)) // Random float between 1.5 and 2.5
console.log(random(-1, 1)) // Random float between -1 and 1
Generate Numbers in a Specific Range
typescript
import { random } from 'radash'
// Generate a dice number between 1 and 6
const dice = random(1, 6, true)
console.log(dice) // 1, 2, 3, 4, 5, or 6
// Generate a digit between 0 and 9
const digit = random(0, 9, true)
console.log(digit) // A number between 0 and 9
// Generate a percentage
const percentage = random(0, 100, true)
console.log(percentage) // A number between 0 and 100
Generate Price Range
typescript
import { random } from 'radash'
// Generate a price between 10 and 100
const price = random(10, 100)
console.log(price) // A number between 10 and 99
// Generate a price with decimals
const priceWithDecimals = random(10, 100) + random(0, 99) / 100
console.log(priceWithDecimals) // A number between 10.00 and 99.99
Generate Color Values
typescript
import { random } from 'radash'
// Generate RGB color values
const r = random(0, 255, true)
const g = random(0, 255, true)
const b = random(0, 255, true)
const rgbColor = `rgb(${r}, ${g}, ${b})`
console.log(rgbColor) // e.g.: rgb(123, 45, 67)
// Generate hexadecimal color
const hexColor = `#${random(0, 16777215, true).toString(16).padStart(6, '0')}`
console.log(hexColor) // e.g.: #7b2d43
Generate Timestamps
typescript
import { random } from 'radash'
// Generate a random timestamp within the past year
const oneYearAgo = Date.now() - 365 * 24 * 60 * 60 * 1000
const randomTimestamp = random(oneYearAgo, Date.now())
console.log(new Date(randomTimestamp)) // Random date within the past year
// Generate a random date within a specific range
const startDate = new Date('2023-01-01').getTime()
const endDate = new Date('2023-12-31').getTime()
const randomDate = new Date(random(startDate, endDate))
console.log(randomDate) // Random date in 2023
Generate Array Indices
typescript
import { random } from 'radash'
const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']
// Randomly select a fruit
const randomIndex = random(0, fruits.length - 1, true)
const randomFruit = fruits[randomIndex]
console.log(randomFruit) // A random fruit name
// Randomly select multiple fruits (without repetition)
function getRandomFruits(array: string[], count: number) {
const shuffled = [...array].sort(() => random(-1, 1))
return shuffled.slice(0, count)
}
const randomFruits = getRandomFruits(fruits, 3)
console.log(randomFruits) // 3 random fruits
Generate Test Data
typescript
import { random } from 'radash'
// Generate random user data
function generateRandomUser() {
const names = ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve']
const cities = ['Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen', 'Hangzhou']
return {
id: random(1, 1000, true),
name: names[random(0, names.length - 1, true)],
age: random(18, 65, true),
city: cities[random(0, cities.length - 1, true)],
score: random(0, 100, true)
}
}
const user = generateRandomUser()
console.log(user)
// e.g.: { id: 123, name: 'Alice', age: 25, city: 'Beijing', score: 85 }
Generate Coordinates
typescript
import { random } from 'radash'
// Generate screen coordinates
const screenWidth = 1920
const screenHeight = 1080
const x = random(0, screenWidth, true)
const y = random(0, screenHeight, true)
console.log(`Coordinates: (${x}, ${y})`) // e.g.: Coordinates: (1234, 567)
// Generate a random point within a circular area
function randomPointInCircle(centerX: number, centerY: number, radius: number) {
const angle = random(0, 2 * Math.PI, true)
const distance = random(0, radius, true)
return {
x: centerX + distance * Math.cos(angle),
y: centerY + distance * Math.sin(angle)
}
}
const point = randomPointInCircle(100, 100, 50)
console.log(point) // A random point within the circle centered at (100,100) with radius 50
Generate Weighted Random Selection
typescript
import { random } from 'radash'
function weightedRandom<T>(items: T[], weights: number[]): T {
const totalWeight = weights.reduce((sum, weight) => sum + weight, 0)
let randomValue = random(0, totalWeight)
for (let i = 0; i < items.length; i++) {
randomValue -= weights[i]
if (randomValue <= 0) {
return items[i]
}
}
return items[items.length - 1]
}
const fruits = ['apple', 'banana', 'cherry']
const weights = [0.5, 0.3, 0.2] // 50%, 30%, 20% probability
const selectedFruit = weightedRandom(fruits, weights)
console.log(selectedFruit) // A fruit selected randomly by weight
Notes
- Range: By default, the maximum value is not included, and the inclusive parameter can be used to include it.
- Floating-Point Numbers: The returned value may be a floating-point number, even if the input is an integer.
- Performance: The performance of generating random numbers is excellent.
- Distribution: The generated random numbers are uniformly distributed.
- Seed: There is no fixed seed, and the result is different each time it is run.
Differences from Other Methods
Math.random()
: Only generates random numbers between 0 and 1.random()
: radash provides a more flexible random number generation.crypto.getRandomValues()
: A more secure random number, but more complex.
Practical Application Scenarios
- Games: Generate random events and values.
- Testing: Generate test data.
- Simulation: Simulate random processes.
- UI: Generate random colors and positions.
- Algorithms: Randomized algorithms and data structures