1.常用groupBy分组
static groupBy(ss: any[], fn: string | ((v) => string | number | bigint)) {
let out = {};
ss.forEach((s) => {
let key = typeof fn == 'string' ? s[fn] : fn(s);
if (!out[key]) {
out[key] = [];
out[key].key = key;
}
out[key].push(s);
});
return Object.keys(out).map((key) => out[key]);
}
调用例子
groupBy(planSections.items, (section) => section.regionName)
2.生成随机字符串
static getRandom(prefix?) {
let d = new Date().getTime();
if (window.performance && typeof window.performance.now === 'function') {
d += performance.now();
}
const _uuid = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(
/[xy]/g,
function (c) {
const r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
}
);
return prefix? `${prefix}${_uuid}`:_uuid;
}
3.拷贝copy
static copy(data: any, copy: boolean = true): any {
if (!copy) return data;
if (data && typeof data === 'object') {
let type = Object.prototype.toString.call(data);
if (type === '[object Date]') return new Date(data.getTime());
let newObj = type === '[object Array]' ? [] : {};
for (var i in data) {
newObj[i] = this.copy(data[i], copy);
}
return newObj;
}
return data;
}
4.数字转中文
static toChinesNum(num) {
let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
let unit = ["", "十", "百", "千", "万"];
num = parseInt(num);
let getWan = (temp) => {
let strArr = temp.toString().split("").reverse();
let newNum = "";
for (var i = 0; i < strArr.length; i++) {
newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
}
return newNum;
}
let overWan = Math.floor(num / 10000);
let noWan = `${num % 10000}`;
if (noWan.toString().length < 4) {
noWan = "0" + noWan;
}
return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
}
5.获取因数
static getFactorArr(num: number) {
const arr = [];
if (!num) {
return arr;
}
for (let i = 1; i <= num; i *= 2) {
if ((i & num) !== 0) {
arr.push(i);
}
}
return arr;
}
6.格式化url
/**
* 格式化url
* @param path 路径
* @param params 参数
* @param splicing 是否将剩余参数拼入路径
*/
static formatUrl(path: string, params: any, splicing = false): string {
if (!params) return path;
let matchList = path.match(/\{\w+\}/gi);
if (matchList && matchList.length) {
matchList.forEach((m) => {
let key = m.substring(1, m.length - 1);
path = path.replace(m, params[key]);
delete params[key];
});
}
Object.keys(params).forEach((v) => {
if (
params[v] == null ||
params[v] == undefined ||
params[v].toString() == ''
)
delete params[v];
});
if (splicing) {
path += '?' + new URLSearchParams(params).toString();
}
return path;
}