2024-09-11 18:49:43 +08:00
|
|
|
|
import {v4 as uuidv4} from 'uuid'
|
2024-08-29 14:42:46 +08:00
|
|
|
|
|
2024-09-03 23:13:58 +08:00
|
|
|
|
/**
|
|
|
|
|
|
* 生成UUID
|
|
|
|
|
|
* @returns {string}
|
|
|
|
|
|
*/
|
2024-08-29 14:42:46 +08:00
|
|
|
|
export function createUUID() {
|
|
|
|
|
|
return uuidv4().replace(/-/g, '')
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2024-09-03 23:13:58 +08:00
|
|
|
|
/**
|
|
|
|
|
|
* 通过字符串生成唯一编码,可能有hash碰撞问题
|
|
|
|
|
|
* @param str
|
|
|
|
|
|
* @returns {number|string}
|
|
|
|
|
|
*/
|
2024-08-29 14:42:46 +08:00
|
|
|
|
export function createHashCodeByStr(str) {
|
|
|
|
|
|
let hash = 0
|
|
|
|
|
|
if (str.length === 0) return hash
|
|
|
|
|
|
for (let i = 0; i < str.length; i++) {
|
|
|
|
|
|
const char = str.charCodeAt(i)
|
|
|
|
|
|
hash = ((hash << 5) - hash) + char
|
|
|
|
|
|
hash = hash & hash // 转换为32位整数
|
|
|
|
|
|
}
|
|
|
|
|
|
// 将整数转换为16进制字符串,以缩短code长度
|
|
|
|
|
|
return Math.abs(hash).toString(16)
|
|
|
|
|
|
}
|
2024-09-11 18:49:43 +08:00
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 生成一个16位的纯数字的唯一ID
|
|
|
|
|
|
* 生成策略 head + 当前时间戳 + 随机数
|
|
|
|
|
|
* @param head 前缀
|
|
|
|
|
|
*/
|
|
|
|
|
|
export function createUniqueCodeByHead(head = '') {
|
|
|
|
|
|
const min = 100; // 最小值
|
|
|
|
|
|
const max = 999; // 最大值
|
|
|
|
|
|
return head.toString() + Date.now().toString() + Math.floor(Math.random() * (max - min + 1)) + min;
|
|
|
|
|
|
}
|