/** * 防抖函数 * @param {Function} func - 要执行的函数 * @param {number} wait - 等待时间(毫秒) */ export const debounce = (fn, wait = 300) => { let t return (...args) => (clearTimeout(t), t = setTimeout(() => fn(...args), wait)) } /** * 节流函数 * @param {Function} func - 要执行的函数 * @param {number} limit - 时间限制(毫秒) */ export const throttle = (fn, limit = 300) => { let t return (...args) => !t && (fn(...args), t = setTimeout(() => t = null, limit)) } /** * 深拷贝(使用原生 API) * @param {any} obj - 要拷贝的对象 */ export const deepClone = (obj) => structuredClone(obj) /** * 生成随机 Id * @param {number} length - 长度 */ export const generateId = (length = 8) => Math.random().toString(36).slice(2, 2 + length) /** * 本地存储工具 */ export const storage = { get: (key, defaultValue = null) => { try { const item = localStorage.getItem(key) return item ? JSON.parse(item) : defaultValue } catch { return defaultValue } }, set: (key, value) => { try { localStorage.setItem(key, JSON.stringify(value)); return true } catch { return false } }, remove: (key) => { try { localStorage.removeItem(key); return true } catch { return false } }, clear: () => { try { localStorage.clear(); return true } catch { return false } } } /** * 检测设备类型 */ export const getDeviceType = () => { const ua = navigator.userAgent if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) return 'tablet' if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) return 'mobile' return 'desktop' } /** * 复制到剪贴板 * @param {string} text - 要复制的文本 */ export const copyToClipboard = (text) => navigator.clipboard.writeText(text).then(() => true).catch(() => false)