工具函数概览
工具函数概览
Section titled “工具函数概览”本文档介绍了 Tiebo 项目中常用的工具函数。
formatFileSize
Section titled “formatFileSize”格式化文件大小显示。
function formatFileSize(bytes: number): string { const units = ['B', 'KB', 'MB', 'GB']; let size = bytes; let unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) { size /= 1024; unitIndex++; }
return `${size.toFixed(1)} ${units[unitIndex]}`;}truncateText
Section titled “truncateText”截断长文本并添加省略号。
function truncateText(text: string, maxLength: number): string { if (text.length <= maxLength) return text; return text.substring(0, maxLength) + '...';}formatDate
Section titled “formatDate”格式化日期显示。
function formatDate(date: Date, format: string = 'YYYY-MM-DD'): string { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0');
return format .replace('YYYY', String(year)) .replace('MM', month) .replace('DD', day);}relativeTime
Section titled “relativeTime”显示相对时间(如:2 小时前)。
function relativeTime(date: Date): string { const now = new Date(); const diff = now.getTime() - date.getTime(); const seconds = Math.floor(diff / 1000); const minutes = Math.floor(seconds / 60); const hours = Math.floor(minutes / 60); const days = Math.floor(hours / 24);
if (days > 0) return `${days} 天前`; if (hours > 0) return `${hours} 小时前`; if (minutes > 0) return `${minutes} 分钟前`; return '刚刚';}unique
Section titled “unique”数组去重。
function unique<T>(array: T[]): T[] { return [...new Set(array)];}将数组分割成指定大小的块。
function chunk<T>(array: T[], size: number): T[][] { const chunks: T[][] = []; for (let i = 0; i < array.length; i += size) { chunks.push(array.slice(i, i + size)); } return chunks;}deepClone
Section titled “deepClone”深拷贝对象。
function deepClone<T>(obj: T): T { if (obj === null || typeof obj !== 'object') return obj; if (obj instanceof Date) return new Date(obj.getTime()) as any; if (obj instanceof Array) return obj.map(item => deepClone(item)) as any;
const cloned = {} as T; for (const key in obj) { if (obj.hasOwnProperty(key)) { cloned[key] = deepClone(obj[key]); } } return cloned;}选择对象中的特定属性。
function pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> { const result = {} as Pick<T, K>; keys.forEach(key => { if (key in obj) { result[key] = obj[key]; } }); return result;}isEmail
Section titled “isEmail”验证邮箱格式。
function isEmail(email: string): boolean { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(email);}isValidUrl
Section titled “isValidUrl”验证 URL 格式。
function isValidUrl(url: string): boolean { try { new URL(url); return true; } catch { return false; }}storage
Section titled “storage”本地存储工具类。
class Storage { static set<T>(key: string, value: T): void { localStorage.setItem(key, JSON.stringify(value)); }
static get<T>(key: string, defaultValue?: T): T | undefined { const item = localStorage.getItem(key); return item ? JSON.parse(item) : defaultValue; }
static remove(key: string): void { localStorage.removeItem(key); }
static clear(): void { localStorage.clear(); }}import { formatFileSize, formatDate, unique, deepClone, isEmail, Storage} from '../utils/helpers';
// 使用工具函数const size = formatFileSize(1024 * 1024); // "1.0 MB"const date = formatDate(new Date(), 'YYYY-MM-DD'); // "2024-01-01"const uniqueArray = unique([1, 2, 2, 3]); // [1, 2, 3]const clonedObj = deepClone(originalObject);const validEmail = isEmail('user@example.com'); // true
// 使用存储工具Storage.set('user', { name: 'John', age: 30 });const user = Storage.get('user');这些工具函数可以在项目中的任何地方使用,提高开发效率和代码复用性。