'use strict';
import moment from 'moment'
/**
?*公共方法類庫
?*/
constutils = {
type: {
'string': '[object String]',
'number': '[object Number]',
'boolean': '[object Boolean]',
'function': '[object Function]',
'array': '[object Array]',
'object': '[object Object]',
'date': '[object Date]',
'null': '[object Null]',
'undefined': '[object Undefined]'
},
isNumber(obj){
return !isNaN(parseInt(obj));
},
isString(obj){
return this.typeOf(obj,'string')
},
isArray(obj){
return this.typeOf(obj,'array')
},
isDate(obj){
return this.typeOf(obj,'date')
},
typeOf(obj,type){
returnObject.prototype.toString.call(obj)=== this.type[type]
},
isMobile,
isEmail,
isChinese,
isIDCard,
timeStampToStr,
strToTimeStamp,
generateMixed,
generateNumber,
inArray,
toThousands,
removeHTMLTag,
getRequestParam,
copyObj,
strLimit,
exchangeSpec,
randInt,
nextInt,
cryptXOR,
timeStampToFriendlyTime,
formatSimilar,
getFuncName,
getGender,
generateSerialNumArray,
getMonthDate,
formatBirth,
numberToTenThousand,
showTime,
sortByPinYin,
formatData,
formatTimer,
stringToBytes,
mbStringLength,
checkIsSymbol,
checkIsChinese,
checkPassword,
replaceAll
}
export defaultutils
/**
?*校驗手機號
?* @param tel
?* @returns {boolean}
?* @constructor
?*/
function isMobile(tel){
letreg = newRegExp(/^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$/);
returntel.match(reg);
}
/**
?*校驗郵箱
?* @param email
?* @constructor
?*/
function isEmail(email){
//let reg = /^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$/;
letreg = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/;
returnemail.match(reg);
}
/**
?*校驗中文
?* @param lang
?* @constructor
?*/
function isChinese(lang){
letreg = /[^\u0000-\u00FF]/;
returnlang.match(reg);
}
/**
?*校驗身份證
?* @param idCard
?* @constructor
?*/
function isIDCard(idCard){
letreg = /^[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)$/;
returnidCard.match(reg);
}
/**
?*時間戳轉(zhuǎn)字符串
?* @param str
?* @param time
?* @param addZero
?* @returns {string|*}
?* @constructor
?*/
function timeStampToStr(time,str,addZero = true){
str =str ?str.toLowerCase(): 'y-m-d h:i:s';
letweeks =['日','一','二','三','四','五','六'];
lett = newDate(time);
letyear =t.getFullYear();
letmonth,day,hour,minute,second;
if(addZero){
month =(t.getMonth()+ 1)< 10 ? '0' +(t.getMonth()+ 1):(t.getMonth()+ 1);
day =t.getDate()< 10 ? '0' +t.getDate():t.getDate();
hour =t.getHours()< 10 ? '0' +t.getHours():t.getHours();
minute =t.getMinutes()< 10 ? '0' +t.getMinutes():t.getMinutes();
second =t.getSeconds()< 10 ? '0' +t.getSeconds():t.getSeconds();
} else {
month =(t.getMonth()+ 1);
day =t.getDate();
hour =t.getHours();
minute =t.getMinutes();
second =t.getSeconds();
}
letweek =weeks[t.getDay()];
returnstr.replace('y',year)
.replace('m',month)
.replace('d',day)
.replace('h',hour)
.replace('i',minute)
.replace('s',second)
.replace('w',week);
}
/**
?*字符串轉(zhuǎn)時間戳
?* @param str
?* @returns {number}
?*/
function strToTimeStamp(str){
if(utils.isString(str)){
str =str.replace(/\-/g,',')
.replace(/ /g,',')
.replace(/:/g,',')
.split(',')
for(letkey instr){
str[key]= parseInt(str[key])
}
return newDate(str[0],str[1]- 1,str[2],str[3],str[4],str[5]).getTime()
}
returnstr;
}
/**
?*生成隨機字符串泞当,大小寫加數(shù)字
?* @param n
?* @returns {string}
?*/
function generateMixed(n){
letchars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ02345789';
letres = "";
for(leti = 0;i <n;i++){
letid =Math.ceil(Math.random()*(chars.length - 1));
res +=chars.charAt(id);
}
returnres;
}
/**
?*判斷給定的元素是否在數(shù)組里阀捅,
?* @param value
?* @param arr
?* @param accurate是否嚴(yán)格匹配,默認(rèn)否
?* @returns {boolean}
?*/
function inArray(arr,value,accurate = false){
if(accurate !== false){
for(letkey ofarr){
if(arr[key]===value){
return true;
}
}
} else {
for(letkey ofarr){
if(arr[key].indexOf(value)!== -1 ||arr[key]==value){
return true;
}
}
}
return false;
}
/**
?*數(shù)字格式化加逗號
?* @param num
?* @returns {string}
?*/
function toThousands(num){
num =(num || 0).toString();
letresult = '';
while(num.length > 3){
result = ',' +num.slice(-3)+result;
num =num.slice(0,num.length - 3);
}
if(num){
result =num +result;
}
returnresult;
}
/**
?*移除HTML標(biāo)簽
?* @param str
?* @returns {string | *}
?*/
function removeHTMLTag(str){
str =str.replace(/<\/?[^>]*>/g,'')//去除HTML tag
.replace(/[|]*\n/g,'\n')//去除行尾空白
.replace(/\n[\s| |]*\r/g,'\n')//去除多余空行
.replace(/ /ig,'');
returnstr;
}
/**
?*獲取請求參數(shù)
?* @param url
?* @returns {*}
?*/
function getRequestParam(url){
if(url.indexOf("?")=== -1)return null;
leturlString =url.substring(url.indexOf("?")+ 1);
leturlArray =urlString.split("&");
leturlObject =[]
for(leti = 0,len =urlArray.length;i <len;i++){
leturlItem =urlArray[i];
letitem =urlItem.split("=");
urlObject[item[0]]=item[1];
}
returnurlObject;
}
/**
?*復(fù)制一個對象
?* @param source
?* @returns {{} & any}
?*/
function copyObj(source){
returnObject.assign({},source)
}
/**
?*超過限制的字符串以省略號形式顯示
?* @param content
?* @param limit
?* @param ellipsis
?* @returns {*}
?*/
function strLimit(content,limit = 50,ellipsis = '……'){
if(content.length <=limit)
returncontent;
returncontent.substring(0,limit)+ellipsis
}
/**
?*生成多種規(guī)格
?* @param doubleArrays必須為二維數(shù)組
?* @returns {*}
?*/
function exchangeSpec(doubleArrays =[
[]
]){
if(!utils.isArray(doubleArrays)){
console.warn('params must be doubleArrays')
return
}
for(letitem ofdoubleArrays){
if(!utils.isArray(item)){
console.warn('params must be doubleArrays')
return
}
}
letlen =doubleArrays.length;
if(len >= 2){
letlen1 =doubleArrays[0].length;
letlen2 =doubleArrays[1].length;
letnewLen =len1 *len2;
lettemp = newArray(newLen);
letindex = 0;
for(leti = 0;i <len1;i++){
for(letj = 0;j <len2;j++){
temp[index]=doubleArrays[0][i]+ '|' +doubleArrays[1][j];
index++;
}
}
letnewArray = newArray(len - 1);
for(leti = 2;i <len;i++){
newArray[i - 1]=doubleArrays[i];
}
newArray[0]=temp;
return exchangeSpec(newArray);
} else {
returndoubleArrays[0];
}
}
/**
?*生成長度為length的隨機數(shù)字
?* @returns {string}
?*/
function generateNumber(length = 1){
constmin = 1
constmax = 21
if(length <=min)length = 1
if(length >=max)length =max
letn = '1';
for(leti = 0;i <length;i++){
n += '0'
}
returnMath.round(Math.random()* parseInt(n));
}
/**
?*隨機生成start - end之間的數(shù)字
?* @param start
?* @param end
?* @returns {*}
?*/
function randInt(start,end){
if(arguments.length <= 1){
return nextInt(start)
}
if(start >end){
console.warn("Start value must be smaller end value.")
return
}
if(start < 0){
console.warn("Both range values must be non-negative.")
return
}
returnstart ===end ?start :start + nextInt(end -start + 1)
}
/**
?*隨機生成0 - bound之前的數(shù)字
?* @param bound
?* @return
?*/
function nextInt(bound = 10){
returnMath.round(Math.random()*bound);
}
/**
?* XOR加解密
?* @param str待加解密的字符串
?* @param key密鑰
?* @returns {string}
?*/
function cryptXOR(str,key = 1234567890){
lettext = '';
for(leti = 0;i <str.length;i++){
text +=String.fromCharCode(str.charCodeAt(i)^key)
}
returntext;
}
function timeStampToFriendlyTime(unixTime){
if(unixTime instanceofDate){
unixTime = newDate(unixTime)
}
unixTime =(unixTime / 1000).toFixed(0)
constnow =(+newDate()/ 1000).toFixed(0)
constsecond =now -unixTime
if(second <= 60){
return '剛剛'
}
else if(Math.floor(second / 60)< 60){
returnMath.floor(second / 60)+ '分鐘前'
}
else if(Math.floor(second / 3600)< 24){
returnMath.floor(second / 3600)+ '小時前'
}
else if(Math.floor(second /(3600 * 24))< 3){
returnMath.floor(second /(3600 * 24))+ '天前'
}
else {
unixTime =unixTime * 1000
constyear = newDate(unixTime).getFullYear()
if(year < newDate().getFullYear()){
return timeStampToStr(unixTime,'y-m-d')
}
return timeStampToStr(unixTime,'m月d日',false)
}
}
/**
?*保留兩位小數(shù)
?* @param similar
?* @returns {any}
?*/
function formatSimilar(similar = 0){
if(!similar ||similar <= 0){
return 0
}
return(similar * 100)=== 100 ? 100 :(similar * 100).toFixed(2)
}
/**
?*獲取函數(shù)名稱
?* @param func
?* @returns {any[]}
?*/
function getFuncName(func){
returnfunc.toString().match(/function\s*(\w*)/i)[1];
}
/**
?*獲取性別
?* @param sex
?* @returns {string}
?*/
function getGender(sex){
if(Number(sex)=== 1){
return '男'
}
else if(Number(sex)=== 2){
return '女'
}
return '未知';
}
/**
?*生成start - end之間的有序數(shù)組
?* @param start
?* @param end
?* @returns {Array}
?*/
function generateSerialNumArray(start,end){
constlen =end -start + 1
letarr =[]
for(leti = 0;i <len;i++){
arr[i]=start +i
}
returnarr
}
/**
?*獲取當(dāng)年月份的天數(shù)
?* @param year
?* @param month
?* @returns {number}
?*/
function getMonthDate(year,month){
return newDate(year,month,0).getDate();
}
/**
?*格式化出生日期
?*/
function formatBirth(birth =[1990,1,1],formatStr = 'y-m-d'){
lety = parseInt(birth[0]);
letm = parseInt(birth[1])>= 10 ? parseInt(birth[1]): '0' + parseInt(birth[1]);
letd = parseInt(birth[2])>= 10 ? parseInt(birth[2]): '0' + parseInt(birth[2]);
returnformatStr.replace('y',y)
.replace('m',m)
.replace('d',d)
}
/**
?*數(shù)字超過后1萬轉(zhuǎn)換單位
?*/
function numberToTenThousand(num,unit = '萬'){
returnnum > 10000 ?(num / 10000).toFixed(0)+unit :num || 0
}
function showTime(msgDate){
msgDate = newDate(msgDate);
letnowDate = newDate();
letresult = "";
letstartTime =nowDate.getTime();
letendTime =msgDate.getTime();
letdates =Math.abs((startTime -endTime))/(1000 * 60 * 60 * 24);
// let d = moment.duration(moment(nowDate,'YYYYMMDD').diff(moment(msgDate,"YYYYMMDD")));
// let dates = d.asDays();
if(dates < 1)//小于24小時
{
if(nowDate.getDate()===msgDate.getDate()){//同一天,顯示時間
result = moment(msgDate).locale("en").format("HH:mm");
} else {
result = moment(msgDate).locale("en").format("昨天HH:mm");
}
}
else if(dates < 2)//昨天
{
letyesterday = newDate(newDate(newDate().toLocaleDateString()).getTime()- 1);
if(msgDate.getDate()===yesterday.getDate()){
result = moment(msgDate).locale("en").format("昨天HH:mm");
} else {
result = moment(msgDate).locale("en").format("前天HH:mm");
}
}
// else if(dates <= 2)//前天
// {
// result = moment(msgDate).format("前天HH:mm");
// }
else if(dates < 7)//一周內(nèi)
{
result = moment(msgDate).locale("en").format("M月D日");
}
else//顯示日期
{
result = moment(msgDate).locale("en").format("YYYY/MM/DD");
}
returnresult;
}
/**
?*按拼音首字符排序
?* @param list
?*/
function sortByPinYin(list =[]){
list.sort((a,b)=> {
returna.letters >b.letters
});
letobj = {};
list.forEach((v,i)=> {
if(!obj[v.letters]){
obj[v.letters]=[];
}
obj[v.letters].push(v);
});
lettemp =obj['#'];
if(temp){
deleteobj['#'];
obj['#']=temp;
}
returnobj;
};
function formatData(arr =[]){
arr.sort(function(a,b){
returnb.createdAt -a.createdAt
});
returnarr;
}
function formatTimer(second = 0){
if(second <= 0){
return '00:00';
}
lets =Math.floor(second);
letm =Math.floor(s / 60);
if(m < 0){
//如果小于一分鐘
returns >= 10 ? '00:' +s : '00:0' +s;
}
else {
s =s >= 10 ?s : '0' +s;
returnm >= 10 ?m + ':' +s : '0' +m + ':' +s;
}
}
function stringToBytes(str){
if(!str || typeofstr !== 'string'){
return[];
}
letch,st,re =[];
for(leti = 0;i <str.length;i++){
ch =str.charCodeAt(i);? // get char
st =[];? ? ? ? ? ? ? ? // set up "stack"
do {
st.push(ch & 0xFF);? // push byte to stack
ch =ch >> 8;? ? ? ? ? // shift value down by 1 byte
}
while(ch);
// add stack contents to result
// done because chars have "wrong" endianness
re =re.concat(st.reverse());
}
// return an array of bytes
returnre;
}
function mbStringLength(str){
returnunescape(encodeURIComponent(str)).length * 8;
}
/**
?*全局替換
?* @param targetStr目標(biāo)字符串
?* @param searchStr要替換的字符串
?* @param replaceStr替換成的字符串
?* @returns {*}
?*/
function replaceAll(targetStr,searchStr,replaceStr){
letreg = newRegExp(searchStr,"g");
returntargetStr.replace(reg,replaceStr);
}
function checkIsSymbol(value){
constpattern = newRegExp("[`~!%@#$^&*()=|{}':;',\\[\\].<>《》/?~音婶!@#¥……&*()——|{}【】‘炎滞;:”“'傅寡。廊敌,哟绊、睡陪?]");
returnpattern.test(value)
}
function checkIsChinese(value){
constpattern = newRegExp("[\\u4E00-\\u9FFF]+","g");
returnpattern.test(value)
}
/**
?*判斷是否含有字母和數(shù)字組合
?* @param str
?* @returns {boolean}
?*/
function checkPassword(str){
constregNum = /[0-9]/;
constregLetter = /[a-zA-Z]/i;
constisNumber =regNum.test(str);
constisLetter =regLetter.test(str);
if(!isNumber || !isLetter){
return false;
}
return true;
};