collect-system/packages/utils/src/random-utils.ts

85 lines
2.6 KiB
TypeScript
Raw Normal View History

2025-02-05 15:10:40 +08:00
/**
*
*
*/
/**
* ( 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));
};