feat(utils): add common utility functions and validation constants
This commit is contained in:
@@ -1,58 +1,26 @@
|
||||
/**
|
||||
* Check if an element has a class
|
||||
* @param {HTMLElement} ele
|
||||
* @param {string} cls
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function hasClass(ele: HTMLElement, cls: string) {
|
||||
return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add class to element
|
||||
* @param {HTMLElement} ele
|
||||
* @param {string} cls
|
||||
*/
|
||||
export function addClass(ele: HTMLElement, cls: string) {
|
||||
if (!hasClass(ele, cls)) ele.className += " " + cls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove class from element
|
||||
* @param {HTMLElement} ele
|
||||
* @param {string} cls
|
||||
*/
|
||||
export function removeClass(ele: HTMLElement, cls: string) {
|
||||
if (hasClass(ele, cls)) {
|
||||
const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
|
||||
ele.className = ele.className.replace(reg, " ");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否是外部链接
|
||||
* 工具函数统一导出
|
||||
*
|
||||
* @param {string} path
|
||||
* @returns {Boolean}
|
||||
* 本文件作为 barrel export,统一管理所有工具函数的导出
|
||||
* 各类工具函数按功能分类存放在不同文件中:
|
||||
* - dom.ts: DOM 操作相关
|
||||
* - validate.ts: 数据验证相关
|
||||
* - format.ts: 数据格式化相关
|
||||
* - download.ts: 文件下载相关
|
||||
* - auth.ts: 权限认证相关
|
||||
* - storage.ts: 本地存储相关
|
||||
* - request.ts: 网络请求相关
|
||||
* - theme.ts: 主题相关
|
||||
*/
|
||||
export function isExternal(path: string) {
|
||||
const isExternal = /^(https?:|http?:|mailto:|tel:)/.test(path);
|
||||
return isExternal;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化增长率,保留两位小数 ,并且去掉末尾的0 取绝对值
|
||||
*
|
||||
* @param growthRate
|
||||
* @returns
|
||||
*/
|
||||
export function formatGrowthRate(growthRate: number) {
|
||||
if (growthRate === 0) {
|
||||
return "-";
|
||||
}
|
||||
// DOM 操作
|
||||
export { hasClass, addClass, removeClass } from "./dom";
|
||||
|
||||
const formattedRate = Math.abs(growthRate * 100)
|
||||
.toFixed(2)
|
||||
.replace(/\.?0+$/, "");
|
||||
return formattedRate + "%";
|
||||
}
|
||||
// 数据验证
|
||||
export { isExternal, isValidURL, isEmail, isMobile } from "./validate";
|
||||
|
||||
// 数据格式化
|
||||
export { formatGrowthRate, formatFileSize, formatNumber, formatCurrency } from "./format";
|
||||
|
||||
// 文件下载
|
||||
export { downloadFile } from "./download";
|
||||
|
||||
Reference in New Issue
Block a user