UNPKG

@mir_king/common

Version:

提供开发中常用的工具函数,提升开发效率的库

542 lines (527 loc) 18.1 kB
export const data = { // 获取之前或者之后的日期 用于组件显示 days 天数 baseDate 时间默认当前时间 为可选参数 dateCalculator(days, baseDate = new Date()) { // 复制日期对象避免污染原值 const date = new Date(baseDate); // 计算天数差值 date.setDate(date.getDate() + days); // 格式化为 yyyy-mm-dd 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}`; }, get7Days() { const endDate = new Date(); // 今天 const startDate = new Date(); startDate.setDate(endDate.getDate() - 6); // 7天前(含今天,共7天) // 格式化为字符串(如 "2023-10-01") const format = (date) => date.toISOString().split("T")[0]; return format(startDate); }, // 表单数据转换 字符串转数组 数组转字符串 dataConversion(value, type = "auto") { // 处理空值情况 if (value === null || value === undefined) { return type === "array" ? [] : ""; } // 自动判断类型转换 if (type === "auto") { type = Array.isArray(value) ? "string" : "array"; } // 数组转字符串 if (type === "string") { if (Array.isArray(value)) { return value.join(","); } // 如果已经是字符串,直接返回 return typeof value === "string" ? value : String(value); } // 字符串转数组 if (type === "array") { if (typeof value === "string") { // 处理前后可能存在的逗号 const str = value.trim(); return str ? str.split(/\s*,\s*/) : []; } // 如果已经是数组,直接返回 return Array.isArray(value) ? value : [value]; } throw new Error(`Invalid conversion type: ${type}`); }, // 根据身份证查询 出生日期 性别 年龄 getAnalysisIdCard(card, num) { if (!card) return null; if (typeof card == "number") card += ""; // 创建档案的身份证 正则 let compliance = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test( card ); console.log("是否正确身份证 ==:", compliance); if (!compliance) return null; let birth = null; let six = null; birth = card.substring(6, 10) + "-" + card.substring(10, 12) + "-" + card.substring(12, 14); if (num == 1) return birth; // 出生日期 six = parseInt(card.substr(16, 1)) % 2 == 1 ? "男" : "女"; if (num == 2) return six; // 获取性别 let myDate = new Date(); let month = myDate.getMonth() + 1; let day = myDate.getDate(); let age = myDate.getFullYear() - card.substring(6, 10) - 1; if ( card.substring(10, 12) < month || (card.substring(10, 12) == month && card.substring(12, 14) <= day) ) { age++; } if (num == 3) return age; //获取年龄 return { birth, six, age, }; }, // 金额输入框 限制输入方法 n 小数位数 amountInput(val, n = 2) { // console.log("限制输入方法 ==:", typeof val, val); if (!val) val = ""; if (typeof val !== "string") val += ""; // console.log('输入 ==:', val); val = val.replace(/。/g, "."); //句号替换为小数点 兼容中文句号 val = val.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符 val = val.replace(/^\./, ""); //清除. 字符开头 val = val.replace(/^00/, "0"); //小数前只能输入一个0 val = val.replace(/^0*(0\.|[1-9])/, "$1"); //解决 粘贴不生效 val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", "."); // 只能输入一个小数点 val = val.replace(new RegExp("(\\.\\d{" + n + "})\\d*"), "$1"); //只能输入n个小数 /(\.\d{2})\d*/ val = val.replace(new RegExp("^0(\\d)"), "$1"); // 01 去掉 0 // console.log('输出 ==:', val); return val; }, // 数字输入框 限制输入方法 n 1:不包括零 0:包括零 numberInput(val, n = 1) { if (!val) val = ""; if (typeof val !== "string") val += ""; // console.log('输入 ==:', val); val = val.replace(/[^\d]/g, ""); //清除“数字”以外的字符 // 是否包括0 if (n == 0) { val = val.replace(/^00/, "0"); //小数前只能输入一个0 val = val.replace(new RegExp("^0(\\d)"), "$1"); // 01 去掉 0 } else { val = val.replace(/^0/, ""); // 替换0 } val = val.replace(/^0*(0\.|[1-9])/, "$1"); //解决 粘贴不生效 // console.log('输出2 ==:', val); return val; }, // 常用正则验证,注意type大小写 checkStr(str, type) { switch (type) { case "phone": // 手机号码 return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str); case "tel": // 座机 return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str); case "card": // 身份证 return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str); case "pwd": // 密码以字母开头,长度在6~18之间,只能包含字母、数字和下划线 return /^[a-zA-Z]\w{5,17}$/.test(str); case "postal": // 邮政编码 return /[1-9]\d{5}(?!\d)/.test(str); case "QQ": // QQ号 return /^[1-9][0-9]{4,9}$/.test(str); case "email": // 邮箱 return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str); case "money": // 金额(小数点2位) return /^\d*(?:\.\d{0,2})?$/.test(str); case "URL": // 网址 return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test( str ); case "IP": // IP return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test( str ); case "date": // 日期时间 return ( /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test( str ) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str) ); case "number": // 数字 return /^[0-9]$/.test(str); case "english": // 英文 return /^[a-zA-Z]+$/.test(str); case "chinese": // 中文 return /^[\u4E00-\u9FA5]+$/.test(str); case "lower": // 小写 return /^[a-z]+$/.test(str); case "upper": // 大写 return /^[A-Z]+$/.test(str); case "HTML": // HTML标记 return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str); default: return true; } }, // 输入一个值,返回其数据类型 type(para) { return Object.prototype.toString.call(para); }, //去除连续的字符串 Setstring(str) { return str.replace(/(\w)\1+/g, "$1"); }, // 随机数 random(min, max) { return parseInt(Math.random() * (max - min)) + min; }, // 不重复随机数 13+4 17位 generateOrderNumber(length = 4) { const data = new Date(); let year = data.getFullYear().toString(); let month = (data.getMonth() + 1).toString(); let day = data.getDate().toString(); let hour = data.getHours().toString(); let minutes = data.getMinutes().toString(); let seconds = data.getSeconds().toString(); // 存放订单号 let num = ""; // N位随机数(加在时间戳后面) for (var i = 0; i < length; i++) { num += Math.floor(Math.random() * 10); } return year + month + day + hour + minutes + seconds + num; }, //重写toFixed方法 toFixed(number, precision = 2) { if (!number) return precision ? "0.00" : "0"; let value = Math.round(+number + "e" + precision) / Math.pow(10, precision); return value.toFixed(precision); }, // 时间转换 TimeData(value, type) { // console.log('时间格式化 ==:', value); let date = value ? new Date(value) : new Date(); let year = date.getFullYear() + ""; let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1 + ""; let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate() + ""; let ymd = year + "-" + month + "-" + day; // yyyy-mm-dd if (type == "yyyy-mm-dd") return ymd; let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours() + ""; let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes() + ""; let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds() + ""; let hms = hours + ":" + minutes + ":" + seconds; // hh:mm:ss if (type == "yyyy-mm-dd hh:mm:ss") return ymd + " " + hms; return { year, month, day, hours, minutes, seconds, DateSplicing_half: ymd, DateSplicing: ymd + " " + hms, DateSplicing_zh: year + "年" + month + "月" + day + "日 " + hours + "时" + minutes + "分" + seconds + "秒", }; }, // 计算时间差 timeDiff(newTime, oldTime) { // 将时分秒转换为秒; function timeToSeconds(time) { let parts = time.split(":"); return parts[0] * 3600 + parts[1] * 60; } // 将秒数转换回时分秒格式 function secondsToTime(seconds) { let hours = Math.floor(seconds / 3600); let minutes = Math.floor((seconds % 3600) / 60); let secs = seconds % 60; return [hours, minutes, secs] .map((num) => num.toString().padStart(2, "0")) .join(":"); } // 将时分秒转换为分 function timeToMinutes(time) { let parts = time.split(":"); let value = parts[0] * 60 + parts[1] * 1 - 480; // console.log('将时分秒转换为分 ==:', time, value < 0 ? 0 : value); return value < 0 ? 0 : value; } // 计算时间差 let numBegin = timeToMinutes(newTime); let numEnd = timeToMinutes(oldTime); let diff = Math.abs(numEnd - numBegin); // 确保是正数 return { minutes: diff, // 换算成分钟 numBegin: numBegin, // 前 numEnd: 720 - numBegin - diff <= 0 ? 0 : 720 - numBegin - diff, // 后 }; }, // 转换字符串,'undefined','null'等转化为'' praseStrEmpty(str) { if (!str || str == "undefined" || str == "null") return ""; return str; }, // 字符串格式化s开头 将字符中s替换成''或者i sprintf(str) { var args = arguments, flag = true, i = 1; str = str.replace(/%s/g, function () { var arg = args[i++]; if (typeof arg === "undefined") { flag = false; return ""; } return arg; }); return flag ? str : ""; }, // 回显 数据字典 selectDictLabel(datas, value) { var actions = []; Object.keys(datas).some((key) => { if (datas[key].dictValue == "" + value) { actions.push(datas[key].dictLabel); return true; } }); return actions.join(""); }, // 回显数据字典(字符串数组) selectDictLabels(datas, value, separator) { var actions = []; var currentSeparator = undefined === separator ? "," : separator; var temp = value.split(currentSeparator); Object.keys(value.split(currentSeparator)).some((val) => { Object.keys(datas).some((key) => { if (datas[key].dictValue == "" + temp[val]) { actions.push(datas[key].dictLabel + currentSeparator); } }); }); return actions.join("").substring(0, actions.join("").length - 1); }, // 构造树型结构数据 data 数据源 id 主键标识 parentId 父节点字段 children 孩子节点字段 handleTree(data, id, parentId, children) { let config = { id: id || "id", parentId: parentId || "parentId", childrenList: children || "children", }; var childrenListMap = {}; var nodeIds = {}; var tree = []; function adaptToChildrenList(o) { if (childrenListMap[o[config.id]] !== null) { o[config.childrenList] = childrenListMap[o[config.id]]; } if (o[config.childrenList]) { for (let c of o[config.childrenList]) { adaptToChildrenList(c); } } } for (let d of data) { let parentId = d[config.parentId]; if (childrenListMap[parentId] == null) { childrenListMap[parentId] = []; } nodeIds[d[config.id]] = d; childrenListMap[parentId].push(d); } for (let d of data) { let parentId = d[config.parentId]; if (nodeIds[parentId] == null) { tree.push(d); } } for (let t of tree) { adaptToChildrenList(t); } return tree; }, // 数据转换,拼接成url参数 params 参数 encodeURIComponent 转换成URT格式的字符串 tansParams(params) { let result = ""; for (const propName of Object.keys(params)) { const value = params[propName]; var part = encodeURIComponent(propName) + "="; if (value !== null && typeof value !== "undefined") { if (typeof value === "object") { for (const key of Object.keys(value)) { let params = propName + "[" + key + "]"; var subPart = encodeURIComponent(params) + "="; result += subPart + encodeURIComponent(value[key]) + "&"; } } else { result += part + encodeURIComponent(value) + "&"; } } } return result; }, //姓名脱敏 handleName(name) { if (!name) return ""; let arr = Array.from(name); let result = ""; if (arr.length === 2) { result = arr[0] + "*"; } else if (arr.length > 2) { for (let i = 1; i < arr.length - 1; i++) { arr[i] = "*"; } result = arr.join(""); } else { return name; } return result; }, // 电话脱敏 handlePhone(phone) { if (!phone) return ""; return phone.replace(/^(.{3})(?:\d+)(.{4})$/, "$1****$2"); }, // 邮箱脱敏 handleEmail(email) { if (!email) return ""; return email.replace(/^(.{0,3}).*@(.*)$/, "$1***@$2"); }, // 身份证脱敏 handleIdCard(id) { if (!id) return ""; return id.replace(/^(.{4})(?:\d+)(.{4})$/, "$1**********$2"); }, // 加法运算 保留小数,默认保留2位 add(num1, num2) { let baseNum, baseNum1, baseNum2; try { baseNum1 = num1.toString().split(".")[1].length; } catch (e) { baseNum1 = 0; } try { baseNum2 = num2.toString().split(".")[1].length; } catch (e) { baseNum2 = 0; } baseNum = Math.pow(10, Math.max(baseNum1, baseNum2)); return (num1 * baseNum + num2 * baseNum) / baseNum; }, // 减法运算 保留小数,默认保留2位 subtract(num1, num2) { let baseNum, baseNum1, baseNum2; let precision; // 精度 try { baseNum1 = num1.toString().split(".")[1].length; } catch (e) { baseNum1 = 0; } try { baseNum2 = num2.toString().split(".")[1].length; } catch (e) { baseNum2 = 0; } baseNum = Math.pow(10, Math.max(baseNum1, baseNum2)); precision = baseNum1 >= baseNum2 ? baseNum1 : baseNum2; return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision); }, // 多个数相减 subtractMul(nums) { if (nums.length < 2) return nums[0] || 0; // 如果数组长度小于2,直接返回第一个数或0 let baseNum, baseNum1, baseNum2; let precision = 0; // 精度 // 获取所有数的小数位数,并确定最大小数位数 let maxDecimalLength = 0; nums.forEach((num) => { try { const decimalLength = num.toString().split(".")[1].length; if (decimalLength > maxDecimalLength) maxDecimalLength = decimalLength; } catch (e) {} }); baseNum = Math.pow(10, maxDecimalLength); // 计算基数 // 初始化结果为第一个数 let result = nums[0] * baseNum; // 依次减去剩余的数 for (let i = 1; i < nums.length; i++) { result -= nums[i] * baseNum; } precision = maxDecimalLength; // 确定最终结果的精度 return (result / baseNum).toFixed(precision); }, // 乘法运算 保留小数,默认保留2位 multiply(num1, num2) { let baseNum = 0; try { baseNum += num1.toString().split(".")[1].length; } catch (e) {} try { baseNum += num2.toString().split(".")[1].length; } catch (e) {} return ( (Number(num1.toString().replace(".", "")) * Number(num2.toString().replace(".", ""))) / Math.pow(10, baseNum) ); }, // 多个乘法运算 保留小数,默认保留2位 multiplyMul(arr) { let baseNum = 0; let result = 1; arr.forEach((num, index) => { try { baseNum += num.toString().split(".")[1].length; } catch (e) {} result *= Number(num.toString().replace(".", "")); }); return this.toFixed(result / Math.pow(10, baseNum)) - 0; }, // 除法运算 保留小数,默认保留2位 divide(num1, num2, digit = 2) { let baseNum1 = 0, baseNum2 = 0; let baseNum3, baseNum4; try { baseNum1 = num1.toString().split(".")[1].length; } catch (e) { baseNum1 = 0; } try { baseNum2 = num2.toString().split(".")[1].length; } catch (e) { baseNum2 = 0; } baseNum3 = Number(num1.toString().replace(".", "")); baseNum4 = Number(num2.toString().replace(".", "")); return ((baseNum3 / baseNum4) * Math.pow(10, baseNum2 - baseNum1)).toFixed( digit ); }, };