doctor-mail/packages/utils/src/index.ts

36 lines
1.4 KiB
TypeScript
Raw Normal View History

2025-01-10 21:36:17 +08:00
/**
* ID
* @param prefix - ID前缀
* @returns ID字符串
*/
export function generateUniqueId(prefix?: string): string {
// 获取当前时间戳
const timestamp = Date.now();
// 生成随机数部分
const randomPart = Math.random().toString(36).substring(2, 8);
// 获取环境特定的额外随机性
const environmentPart = typeof window !== 'undefined'
? window.crypto.getRandomValues(new Uint32Array(1))[0].toString(36)
: require('crypto').randomBytes(4).toString('hex');
// 组合所有部分
const uniquePart = `${timestamp}${randomPart}${environmentPart}`;
// 如果提供了前缀,则添加前缀
return prefix ? `${prefix}_${uniquePart}` : uniquePart;
2025-01-25 02:27:40 +08:00
}
2025-01-26 16:05:24 +08:00
export const formatFileSize = (bytes: number) => {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
};
2025-01-26 19:36:54 +08:00
// 压缩图片路径生成函数
export const getCompressedImageUrl = (originalUrl: string): string => {
const cleanUrl = originalUrl.split(/[?#]/)[0] // 移除查询参数和哈希
const lastSlashIndex = cleanUrl.lastIndexOf('/')
return `${cleanUrl.slice(0, lastSlashIndex)}/compressed/${cleanUrl.slice(lastSlashIndex + 1).replace(/\.[^.]+$/, '.webp')}`
}
2025-01-25 02:27:40 +08:00
export * from "./types"