38 lines
883 B
TypeScript
38 lines
883 B
TypeScript
/**
|
|
* Random utilities
|
|
*/
|
|
|
|
/**
|
|
* Returns true with the given probability (0-1)
|
|
*/
|
|
export function chance(probability: number): boolean {
|
|
return Math.random() < probability;
|
|
}
|
|
|
|
/**
|
|
* Pick a random element from an array
|
|
*/
|
|
export function randomElement<T>(array: T[]): T | undefined {
|
|
if (array.length === 0) return undefined;
|
|
return array[Math.floor(Math.random() * array.length)];
|
|
}
|
|
|
|
/**
|
|
* Shuffle an array (Fisher-Yates)
|
|
*/
|
|
export function shuffle<T>(array: T[]): T[] {
|
|
const result = [...array];
|
|
for (let i = result.length - 1; i > 0; i--) {
|
|
const j = Math.floor(Math.random() * (i + 1));
|
|
[result[i], result[j]] = [result[j], result[i]];
|
|
}
|
|
return result;
|
|
}
|
|
|
|
/**
|
|
* Generate a random integer between min and max (inclusive)
|
|
*/
|
|
export function randomInt(min: number, max: number): number {
|
|
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
}
|