cooperation
Version:
138 lines (124 loc) • 3.29 kB
JavaScript
module.exports = {
/**
* 获取数组最大最小值
* @param arr
* @param type
* @returns {number}
*/
arrMaxMin: (arr, type = 'max') => type === 'max' ? Math.max(...arr) : Math.min(...arr),
/**
* 转驼峰写法
* @param str
* @returns {string | void | *}
*/
camelize: str => (!str.includes('-') && !str.includes('_'))
? str
: str.replace(/[-_][^-_]/g, match => match.charAt(1).toUpperCase()),
/**
* 首字母大写
* @param str
* @returns {string}
*/
capitalize: str => str.charAt(0).toUpperCase() + str.substring(1),
/**
* 差集
* @param arr1
* @param arr2
* @returns {*[]}
*/
difference: (arr1, arr2) => [...new Set([...arr1].filter(x => !arr2.has(x)))],
/**
* 数组去重
* @param arr
* @returns {*[]}
*/
distinct: arr => [...new Set(arr)],
/**
* 交集
* @param arr1
* @param arr2
* @returns {*[]}
*/
intersect: (arr1, arr2) => [...new Set([...arr1].filter(x => arr2.has(x)))],
/**
* 向数组的尾部拼接数组
* @param tagArr 目标数组
* @param endArr 尾部数组
* @returns {*|number}
*/
pushEnd: (tagArr, endArr) => tagArr.push(...endArr),
/**
* 随机字母
* @param len
* @param type
* @returns {string}
*/
randomChar: (len = 4, type = 'upper') => {
let rc = '';
for (let i = 0; i < len; ++i)
rc += String.fromCharCode(65 + Math.ceil(Math.random() * 25));
return type === 'upper' ? rc : rc.toLowerCase();
},
/**
* 随机数
* @param minNum
* @param maxNum
* @returns {number}
*/
randomNum: (minNum = 0, maxNum = 1000) => parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10),
/**
* 获取文本的长度,兼容各种码点的长度
* @param str
* @returns {number}
*/
strLength: str => {
let size = 0;
for (let i of str) ++size;
return size;
},
/**
* 字符的截断处理
* @param str
* @param length
* @param truncation
* @returns {string}
*/
truncate: (str, length = 30, truncation = '...') => str.length > length
? str.slice(0, length - truncation.length) + truncation
: str,
/**
* 转划线写法
* @param str
* @param type
* @returns {string}
*/
underscored: (str, type = '-') => str.replace(/([a-z\d])([A-Z])/g, '$1' + type + '$2').replace(/\-/g, type).toLowerCase(),
/**
* 实体转html
* @param str
* @returns {string}
*/
unescapeHTML: str => str.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, "&") //处理转义的中文和实体字符
.replace(
/&#([\d]+);/g,
($0, $1) => String.fromCharCode(parseInt($1, 10))
),
/**
* 并集
* @param arr1
* @param arr2
* @returns {*[]}
*/
union: (arr1, arr2) => [...new Set([...arr1, ...arr2])],
/**
* 获取请求的ip
* @returns {*|string[]}
*/
reqIp(req) {
console.log(req.connection);
return ip;
}
};