import { util } from '@kit.ArkTS';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';/*** 随机工具类* author: 鸿蒙布道师* since: 2025/04/01*/
export class RandomUtil {/*** 生成随机布尔值* @returns true 或 false*/static getRandomBoolean(): boolean {return Math.random() >= 0.5;}/*** 生成指定范围内的随机整数* @param min 最小值(包含)* @param max 最大值(不包含)* @returns 随机整数*/static getRandomInt(min: number = 0, max: number = Number.MAX_SAFE_INTEGER): number {return Math.floor(Math.random() * (max - min) + min);}/*** 生成指定范围内的随机浮点数* @param min 最小值(包含)* @param max 最大值(不包含)* @returns 随机浮点数*/static getRandomNumber(min: number, max: number): number {return Math.random() * (max - min) + min;}/*** 生成 [0, limit) 范围内的随机整数* @param limit 上限值(不包含)* @returns 随机整数*/static getRandomLimit(limit: number): number {return Math.floor(Math.random() * limit);}/*** 生成一个随机汉字(Unicode 范围 '\u4E00'-'\u9FFF')* @returns 随机的汉字字符*/static getRandomChineseChar(): string {const start = 0x4e00; // 汉字起始 Unicode 编码const end = 0x9fff; // 汉字结束 Unicode 编码return String.fromCharCode(RandomUtil.getRandomInt(start, end + 1));}/*** 生成指定长度的随机汉字字符串* @param length 目标长度* @returns 随机汉字字符串*/static getRandomChinese(length: number): string {return Array.from<string, string>({ length }, (): string => RandomUtil.getRandomChineseChar()).join('');}/*** 根据指定字符池生成随机字符串* @param length 目标长度* @param strPool 字符池* @returns 随机字符串*/static getRandomStr(length: number, strPool: string): string {const poolLength = strPool.length;return Array.from<string, string>({ length }, (): string => strPool[RandomUtil.getRandomLimit(poolLength)]).join('');}/*** 生成随机颜色(十六进制格式)* @returns 十六进制颜色字符串*/static getRandomColor(): string {const hexadecimal = '0123456789ABCDEF'.split(''); // 将字符串拆分为字符数组return '#' + Array.from<string, string>({ length: 6 }, (): string => hexadecimal[RandomUtil.getRandomLimit(16)]).join('');}/*** 生成随机指定长度的 DataBlob* @param length 数据长度* @returns DataBlob 对象*/static getRandomDataBlob(length: number): cryptoFramework.DataBlob {return cryptoFramework.createRandom().generateRandomSync(length);}/*** 生成随机指定长度的 Uint8Array* @param length 数据长度* @returns Uint8Array 数据*/static getRandomUint8Array(length: number): Uint8Array {return RandomUtil.getRandomDataBlob(length).data;}/*** 生成 36 位 UUID(带分隔符)* @returns 36 位 UUID 字符串*/static generateUUID36(): string {return RandomUtil.generateUUIDInternal(36, [8, 13, 18, 23]);}/*** 生成 32 位 UUID(带分隔符)* @returns 32 位 UUID 字符串*/static generateUUID32(): string {return RandomUtil.generateUUIDInternal(32, [8, 12, 16, 20]);}/*** 内部方法:生成通用 UUID* @param length UUID 总长度* @param separators 分隔符位置数组* @returns UUID 字符串*/private static generateUUIDInternal(length: number, separators: number[]): string {const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');let rand = 0;// 使用 Array.from 并显式指定泛型参数return Array.from<string, string>({ length }, // 第一个泛型参数:输入对象的类型(_, i): string => { // 第二个泛型参数:回调函数返回值的类型if (separators.includes(i)) return '-'; // 插入分隔符if (i === 14) return '4'; // UUID 版本号(第14位固定为4)if (rand <= 0x02) rand = 0x2000000 + Math.random() * 0x1000000 | 0; // 更新随机数缓存const r = rand & 0xf; // 取低4位rand >>= 4; // 移动到下一个4位return chars[(i === 19 || i === 12) ? (r & 0x3) | 0x8 : r];}).join(''); // 将字符数组拼接成字符串}/*** 使用加密安全随机数生成器生成 RFC 4122 版本 4 的字符串类型 UUID* @param entropyCache 是否使用缓存,默认 true* @returns UUID 字符串*/static generateRandomUUID(entropyCache: boolean = true): string {return util.generateRandomUUID(entropyCache);}/*** 使用加密安全随机数生成器生成 RFC 4122 版本 4 的 Uint8Array 类型 UUID* @param entropyCache 是否使用缓存,默认 true* @returns Uint8Array 数据*/static generateRandomBinaryUUID(entropyCache: boolean = true): Uint8Array {return util.generateRandomBinaryUUID(entropyCache);}
}代码如下:
import { util } from '@kit.ArkTS';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';/*** 随机工具类* author: 鸿蒙布道师* since: 2025/04/01*/
export class RandomUtil {/*** 生成随机布尔值* @returns true 或 false*/static getRandomBoolean(): boolean {return Math.random() >= 0.5;}/*** 生成指定范围内的随机整数* @param min 最小值(包含)* @param max 最大值(不包含)* @returns 随机整数*/static getRandomInt(min: number = 0, max: number = Number.MAX_SAFE_INTEGER): number {return Math.floor(Math.random() * (max - min) + min);}/*** 生成指定范围内的随机浮点数* @param min 最小值(包含)* @param max 最大值(不包含)* @returns 随机浮点数*/static getRandomNumber(min: number, max: number): number {return Math.random() * (max - min) + min;}/*** 生成 [0, limit) 范围内的随机整数* @param limit 上限值(不包含)* @returns 随机整数*/static getRandomLimit(limit: number): number {return Math.floor(Math.random() * limit);}/*** 生成一个随机汉字(Unicode 范围 '\u4E00'-'\u9FFF')* @returns 随机的汉字字符*/static getRandomChineseChar(): string {const start = 0x4e00; // 汉字起始 Unicode 编码const end = 0x9fff; // 汉字结束 Unicode 编码return String.fromCharCode(RandomUtil.getRandomInt(start, end + 1));}/*** 生成指定长度的随机汉字字符串* @param length 目标长度* @returns 随机汉字字符串*/static getRandomChinese(length: number): string {return Array.from<string, string>({ length }, (): string => RandomUtil.getRandomChineseChar()).join('');}/*** 根据指定字符池生成随机字符串* @param length 目标长度* @param strPool 字符池* @returns 随机字符串*/static getRandomStr(length: number, strPool: string): string {const poolLength = strPool.length;return Array.from<string, string>({ length }, (): string => strPool[RandomUtil.getRandomLimit(poolLength)]).join('');}/*** 生成随机颜色(十六进制格式)* @returns 十六进制颜色字符串*/static getRandomColor(): string {const hexadecimal = '0123456789ABCDEF'.split(''); // 将字符串拆分为字符数组return '#' + Array.from<string, string>({ length: 6 }, (): string => hexadecimal[RandomUtil.getRandomLimit(16)]).join('');}/*** 生成随机指定长度的 DataBlob* @param length 数据长度* @returns DataBlob 对象*/static getRandomDataBlob(length: number): cryptoFramework.DataBlob {return cryptoFramework.createRandom().generateRandomSync(length);}/*** 生成随机指定长度的 Uint8Array* @param length 数据长度* @returns Uint8Array 数据*/static getRandomUint8Array(length: number): Uint8Array {return RandomUtil.getRandomDataBlob(length).data;}/*** 生成 36 位 UUID(带分隔符)* @returns 36 位 UUID 字符串*/static generateUUID36(): string {return RandomUtil.generateUUIDInternal(36, [8, 13, 18, 23]);}/*** 生成 32 位 UUID(带分隔符)* @returns 32 位 UUID 字符串*/static generateUUID32(): string {return RandomUtil.generateUUIDInternal(32, [8, 12, 16, 20]);}/*** 内部方法:生成通用 UUID* @param length UUID 总长度* @param separators 分隔符位置数组* @returns UUID 字符串*/private static generateUUIDInternal(length: number, separators: number[]): string {const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');let rand = 0;// 使用 Array.from 并显式指定泛型参数return Array.from<string, string>({ length }, // 第一个泛型参数:输入对象的类型(_, i): string => { // 第二个泛型参数:回调函数返回值的类型if (separators.includes(i)) return '-'; // 插入分隔符if (i === 14) return '4'; // UUID 版本号(第14位固定为4)if (rand <= 0x02) rand = 0x2000000 + Math.random() * 0x1000000 | 0; // 更新随机数缓存const r = rand & 0xf; // 取低4位rand >>= 4; // 移动到下一个4位return chars[(i === 19 || i === 12) ? (r & 0x3) | 0x8 : r];}).join(''); // 将字符数组拼接成字符串}/*** 使用加密安全随机数生成器生成 RFC 4122 版本 4 的字符串类型 UUID* @param entropyCache 是否使用缓存,默认 true* @returns UUID 字符串*/static generateRandomUUID(entropyCache: boolean = true): string {return util.generateRandomUUID(entropyCache);}/*** 使用加密安全随机数生成器生成 RFC 4122 版本 4 的 Uint8Array 类型 UUID* @param entropyCache 是否使用缓存,默认 true* @returns Uint8Array 数据*/static generateRandomBinaryUUID(entropyCache: boolean = true): Uint8Array {return util.generateRandomBinaryUUID(entropyCache);}
}