This commit is contained in:
2025-12-05 15:41:32 +08:00
commit 7339c71fc0
1433 changed files with 37574 additions and 0 deletions

127
utils/util.js Normal file
View File

@@ -0,0 +1,127 @@
// utils/util.js - 通用工具函数
/**
* 格式化日期时间
* @param {Date|number|string} date - 日期
* @param {string} format - 格式化模板
*/
const formatTime = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
if (!date) return '';
const d = new Date(date);
if (isNaN(d.getTime())) return '';
const year = d.getFullYear();
const month = d.getMonth() + 1;
const day = d.getDate();
const hour = d.getHours();
const minute = d.getMinutes();
const second = d.getSeconds();
const formatNumber = n => n.toString().padStart(2, '0');
return format
.replace('YYYY', year)
.replace('MM', formatNumber(month))
.replace('DD', formatNumber(day))
.replace('HH', formatNumber(hour))
.replace('mm', formatNumber(minute))
.replace('ss', formatNumber(second));
};
/**
* 相对时间格式化刚刚、5分钟前
* @param {Date|number|string} date - 日期
*/
const formatRelativeTime = (date) => {
if (!date) return '';
const d = new Date(date);
const now = new Date();
const diff = now.getTime() - d.getTime();
const minute = 60 * 1000;
const hour = 60 * minute;
const day = 24 * hour;
const month = 30 * day;
const year = 365 * day;
if (diff < minute) {
return '刚刚';
} else if (diff < hour) {
return `${Math.floor(diff / minute)}分钟前`;
} else if (diff < day) {
return `${Math.floor(diff / hour)}小时前`;
} else if (diff < month) {
return `${Math.floor(diff / day)}天前`;
} else if (diff < year) {
return `${Math.floor(diff / month)}个月前`;
} else {
return `${Math.floor(diff / year)}年前`;
}
};
/**
* 防抖函数
* @param {Function} fn - 要防抖的函数
* @param {number} delay - 延迟时间
*/
const debounce = (fn, delay = 300) => {
let timer = null;
return function (...args) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
};
/**
* 节流函数
* @param {Function} fn - 要节流的函数
* @param {number} interval - 间隔时间
*/
const throttle = (fn, interval = 300) => {
let lastTime = 0;
return function (...args) {
const now = Date.now();
if (now - lastTime >= interval) {
lastTime = now;
fn.apply(this, args);
}
};
};
/**
* 深拷贝
* @param {any} obj - 要拷贝的对象
*/
const deepClone = (obj) => {
if (obj === null || typeof obj !== 'object') return obj;
if (obj instanceof Date) return new Date(obj);
if (obj instanceof Array) return obj.map(item => deepClone(item));
if (obj instanceof Object) {
const copy = {};
Object.keys(obj).forEach(key => {
copy[key] = deepClone(obj[key]);
});
return copy;
}
return obj;
};
/**
* 生成唯一ID
*/
const generateId = () => {
return Date.now().toString(36) + Math.random().toString(36).substr(2, 9);
};
module.exports = {
formatTime,
formatRelativeTime,
debounce,
throttle,
deepClone,
generateId
};