joel bot
This commit is contained in:
37
src/utils/random.ts
Normal file
37
src/utils/random.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
Reference in New Issue
Block a user