training_data/packages/utils/src/random-utils.ts

85 lines
2.6 KiB
TypeScript
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 随机工具函数库
* 提供生成随机数、随机字符串、随机数组等功能。
*/
/**
* 生成一个指定范围内的随机整数 (包含 min 和 max)
* @param min 最小值 (包含)
* @param max 最大值 (包含)
*/
export const getRandomInt = (min: number, max: number): number => {
const minimum = Math.ceil(min);
const maximum = Math.floor(max);
return Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
};
/**
* 生成一个指定长度的随机字符串
* @param length 随机字符串的长度
* @param chars 可选,使用的字符集,默认是字母 (大小写) 和数字
*/
export const getRandomString = (length: number, chars: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'): string => {
let result = '';
const charsLength = chars.length;
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * charsLength));
}
return result;
};
/**
* 生成一个随机布尔值 (true 或 false)
*/
export const getRandomBoolean = (): boolean => {
return Math.random() >= 0.5;
};
/**
* 从数组中随机选取一个值
* @param array 要随机提取的数组
*/
export const getRandomFromArray = <T>(array: T[]): T => {
return array[Math.floor(Math.random() * array.length)];
};
/**
* 打乱一个数组
* @param array 要打乱的数组
*/
export const shuffleArray = <T>(array: T[]): T[] => {
const shuffled = [...array]; // 创建一个副本以免修改原数组
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
};
/**
* 生成一个随机的十六进制颜色代码 (如 "#a1b2c3")
*/
export const getRandomHexColor = (): string => {
return `#${Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0')}`;
};
/**
* 生成一个随机RGBA颜色
* @param alpha 可选,透明度 (范围 0-1)
*/
export const getRandomRGBAColor = (alpha: number = 1): string => {
const r = getRandomInt(0, 255);
const g = getRandomInt(0, 255);
const b = getRandomInt(0, 255);
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
};
/**
* 随机延迟一段时间 (返回一个 Promise在随机时间后 resolve)
* @param min 最小延迟时间 (毫秒)
* @param max 最大延迟时间 (毫秒)
*/
export const randomDelay = (min: number, max: number): Promise<void> => {
const delay = getRandomInt(min, max);
return new Promise(resolve => setTimeout(resolve, delay));
};