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

42 lines
1.4 KiB
TypeScript

/**
* 生成唯一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;
}
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`;
};
// 压缩图片路径生成函数
export const getCompressedImageUrl = (originalUrl: string): string => {
if (!originalUrl) {
return originalUrl;
}
const cleanUrl = originalUrl.split(/[?#]/)[0]; // 移除查询参数和哈希
const lastSlashIndex = cleanUrl.lastIndexOf("/");
return `${cleanUrl.slice(0, lastSlashIndex)}/compressed/${cleanUrl.slice(lastSlashIndex + 1).replace(/\.[^.]+$/, ".webp")}`;
};
export * from "./types";