admin-vben5/packages/@core/shared/toolkit/src/hash.ts
2024-06-08 21:27:43 +08:00

32 lines
1007 B
TypeScript
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.

/**
* 生成一个UUID通用唯一标识符
*
* UUID是一种用于软件构建的标识符其目的是能够生成一个唯一的ID以便在全局范围内标识信息。
* 此函数用于生成一个符合version 4的UUID这种UUID是随机生成的。
*
* 生成的UUID的格式为xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
* 其中x是任意16进制数字y是一个16进制数字取值范围为[8, b]。
*
* @returns {string} 生成的UUID。
*/
function generateUUID(): string {
let d = Date.now();
if (
typeof performance !== 'undefined' &&
typeof performance.now === 'function'
) {
d += performance.now(); // use high-precision timer if available
}
const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replaceAll(
/[xy]/g,
(c) => {
const r = Math.trunc((d + Math.random() * 16) % 16);
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
},
);
return uuid;
}
export { generateUUID };