// 日期格式化算法
export function dateFormater(milliseconds) {
if (!milliseconds) return '';
const date = new Date(milliseconds);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
// 時(shí)間格式化
export function timeFormater(milliseconds) {
if (!milliseconds) return '';
const date = new Date(milliseconds);
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return `${hours}:${minutes}:${seconds}`;
}
// 完整日期時(shí)間格式化
export function datetimeFormater(milliseconds) {
const dateStr = dateFormater(milliseconds);
const timeStr = timeFormater(milliseconds);
return `${dateStr} ${timeStr}`;
}
// 金額格式化(保留兩位小數,千分位)
export function amountFormater(amount) {
if (amount === null || amount === undefined) return '0.00';
const num = parseFloat(amount);
if (isNaN(num)) return '0.00';
return num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
// 數字格式化(千分位)
export function numberFormater(num, decimals = 2) {
if (num === null || num === undefined) return '0';
const number = parseFloat(num);
if (isNaN(number)) return '0';
return number.toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
// 百分比格式化
export function percentFormater(value, decimals = 2) {
if (value === null || value === undefined) return '0%';
const num = parseFloat(value) * 100;
if (isNaN(num)) return '0%';
return `${num.toFixed(decimals)}%`;
}
// 文件大小格式化
export function fileSizeFormater(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
// 郵箱驗證
export function validateEmail(email) {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(String(email).toLowerCase());
}
// 手機號驗證
export function validatePhone(phone) {
const re = /^1[3-9]\d{9}$/;
return re.test(String(phone));
}
// 身份證驗證
export function validateIDCard(idCard) {
const re = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
return re.test(String(idCard));
}
// 統一社會(huì )信用代碼驗證
export function validateCreditCode(code) {
const re = /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/;
return re.test(String(code));
}
// 報關(guān)單號驗證
export function validateEntryId(entryId) {
if (!entryId) return false;
// 報關(guān)單號規則:字母+數字,長(cháng)度8-18位
const re = /^[A-Za-z0-9]{8,18}$/;
return re.test(entryId);
}
// 商品編碼驗證
export function validateProductCode(code) {
if (!code) return false;
// 商品編碼規則:8位或10位數字
const re = /^\d{8}(\d{2})?$/;
return re.test(code);
}
// 金額驗證
export function validateAmount(amount) {
if (amount === null || amount === undefined) return false;
const num = parseFloat(amount);
if (isNaN(num)) return false;
// 金額不能為負數,且最多保留2位小數
return num >= 0 && /^\d+(\.\d{1,2})?$/.test(amount.toString());
}
// 數量驗證
export function validateQuantity(qty) {
if (qty === null || qty === undefined) return false;
const num = parseFloat(qty);
if (isNaN(num)) return false;
// 數量必須為正數,且為整數
return num > 0 && Number.isInteger(num);
}
// 安全轉換為數字
export function safeToNumber(value, defaultValue = 0) {
if (value === null || value === undefined) return defaultValue;
const num = parseFloat(value);
return isNaN(num) ? defaultValue : num;
}
// 安全轉換為字符串
export function safeToString(value, defaultValue = '') {
if (value === null || value === undefined) return defaultValue;
return String(value);
}
// 安全轉換為布爾值
export function safeToBoolean(value, defaultValue = false) {
if (value === null || value === undefined) return defaultValue;
if (typeof value === 'boolean') return value;
if (typeof value === 'number') return value !== 0;
if (typeof value === 'string') {
return value.toLowerCase() === 'true' || value === '1';
}
return defaultValue;
}
// 對象數組轉Map
export function arrayToMap(array, keyField) {
if (!Array.isArray(array)) return new Map();
const map = new Map();
array.forEach(item => {
if (item && item[keyField] !== undefined) {
map.set(item[keyField], item);
}
});
return map;
}
// Map轉對象數組
export function mapToArray(map) {
return Array.from(map.values());
}
// 對象轉查詢(xún)字符串
export function objectToQueryString(obj) {
if (!obj || typeof obj !== 'object') return '';
const params = new URLSearchParams();
Object.keys(obj).forEach(key => {
if (obj[key] !== null && obj[key] !== undefined) {
params.append(key, String(obj[key]));
}
});
return params.toString();
}
// 查詢(xún)字符串轉對象
export function queryStringToObject(queryString) {
const params = new URLSearchParams(queryString);
const obj = {};
for (const [key, value] of params) {
obj[key] = value;
}
return obj;
}
// 數組求和
export function sumArray(arr) {
if (!Array.isArray(arr)) return 0;
return arr.reduce((total, current) => {
const num = safeToNumber(current);
return total + num;
}, 0);
}
// 數組平均值
export function averageArray(arr) {
if (!Array.isArray(arr) || arr.length === 0) return 0;
const total = sumArray(arr);
return total / arr.length;
}
// 數組最大值
export function maxArray(arr) {
if (!Array.isArray(arr) || arr.length === 0) return 0;
return Math.max(...arr.map(item => safeToNumber(item)));
}
// 數組最小值
export function minArray(arr) {
if (!Array.isArray(arr) || arr.length === 0) return 0;
return Math.min(...arr.map(item => safeToNumber(item)));
}
// 計算商品總金額
export function calculateTotalAmount(goodsList) {
if (!Array.isArray(goodsList)) return 0;
return goodsList.reduce((total, goods) => {
const quantity = safeToNumber(goods.qty);
const price = safeToNumber(goods.price);
return total + (quantity * price);
}, 0);
}
// 計算稅額
export function calculateTax(amount, taxRate) {
const total = safeToNumber(amount);
const rate = safeToNumber(taxRate) / 100;
return total * rate;
}
// 計算退稅額
export function calculateTaxRefund(amount, refundRate) {
const total = safeToNumber(amount);
const rate = safeToNumber(refundRate) / 100;
return total * rate;
}
// 匯率換算
export function currencyConvert(amount, exchangeRate) {
const total = safeToNumber(amount);
const rate = safeToNumber(exchangeRate);
return total * rate;
}
這些數據處理算法為應用提供了強大的數據轉換、驗證和計算能力,確保數據的準確性和一致性。