查询Tree结构数组指定字段的父结构
/**
* 查询Tree结构数组指定字段的父结构 Promise
* @param {Array} arr Tree[]
* @param {String} currentValue 需要查询的当前元素的值
* @param {Array} option [0]需要查询的key[1]子节点数组keyName,默认:['id','children']
* @returns {Array} 返回查询到的全部父节点的数组
* @example
* setQueryParentStructure([{id: 1,name: 'name1', child: [{id: 11,name: 'name11'}, {id: 12,name: 'name12'}]}]);
*/
export function setQueryParentStructure(arr = [], currentValue = '', option = ['id', 'children']) {
return new Promise((resolve, reject) => {
if (!Array.isArray(arr) || !arr || arr.length < 0 || !currentValue || !option) {
reject(`参数错误`)
}
const searchParent: any = []
function callback(arr = [], currentValue = '', option = ['id', 'children'], parent = {}) {
arr.forEach((item) => {
if (item?.[option?.[0]] === currentValue) {
searchParent.push(parent)
} else {
const child = item?.[option?.[1]]
if (Array.isArray(child) && child && child.length > 0) {
callback(child, currentValue, option, item)
}
}
})
}
callback(arr, currentValue, option, searchParent)
resolve(searchParent)
})
}
颜色转换
/**
* 颜色转换 Promise
* @param {String} color 颜色
* @param {String} type 转换类型 'rgba' || '#'
* @param {Number} aVal 当需要透明度时的值
* @returns {String} 颜色
* @example
* GetColorChange('#f00', 'rgba', 1); // rgba(255,0,0,1)
* GetColorChange('rgb(255,0,0)', '#'); // #ff0000
*/
export function GetColorChange(color, type = 'rgba', aVal = 1) {
return new Promise((resolve, reject) => {
function checkColorFormat() {
const regex = /^(rgba?|#)/i;
return regex.test(color);
}
if (!checkColorFormat()||!['rgba', '#'].includes(type)) {
reject(
`GetColorChange(color, type, 'a(不必填)');type: '#' || 'rgba'
使用方法:GetColorChange('rgb(255,0,0)', '#')
使用方法:GetColorChange('#f00', 'rgba')
`
)
}
if (type === 'rgba') {
if (color.indexOf('#') > -1) {
const colorArr = color.split('')
const tempColor = color.length === 4 ? `${colorArr[1]}${colorArr[1]}${colorArr[2]}${colorArr[2]}${colorArr[3]}${colorArr[3]}` : color.replace('#', '')
const r = parseInt(tempColor.slice(0, 2), 16);
const g = parseInt(tempColor.slice(2, 4), 16);
const b = parseInt(tempColor.slice(4, 6), 16);
const a = tempColor.length === 6 ? aVal : parseInt(tempColor.slice(6, 8), 16);
resolve(`rgba(${r},${g},${b},${a})`)
} else {
if (color.indexOf('rgba') > -1) {
const arr = color.split(',').filter((_n, i, carr) => i !== carr.length - 1)
resolve(`${arr.join(',')},${aVal})`)
} else {
const arr = color.replace(')', '').split(',')
arr[0] = arr[0].replace('rgb', 'rgba')
resolve(`${arr.join(',')},${aVal})`)
}
}
} else if (type === '#') {
if (color.indexOf('#') > -1) {
resolve(color)
} else {
const tempColor = color.replace('rgb', '').replace('a', '').replace(/\(|\)/g, "").split(',')
const toRgb = (value) => {
const t = value.length === 1 ? '0' + value : value
return Math.round(t).toString(16).padStart(2, '0')
};
const isA = color.indexOf('rgba') > -1
const red = toRgb(tempColor[0]);
const green = toRgb(tempColor[1]);
const blue = toRgb(tempColor[2]);
const alpha = isA ? Math.round(tempColor[3] * 255).toString(16).padStart(2, '0') : aVal;
resolve(`#${red}${green}${blue}${isA ? alpha : ''}`)
}
}
})
}
toFixed四舍五入 五不五入
/**
* toFixed四舍五入 五不五入 Promise
* @param {Number} value 小数
* @param {Number} digst 截取小数位数
* @returns {Number} 小数
* @example
* GetToFixeds(1.45, 1); // 1.5
*/
export function GetToFixeds(value, digst = 0) {
return new Promise((resolve) => {
let value1 = value + "";
if (value1.indexOf(".") == -1) value1 += ".";
value1 += new Array(digst + 1).join("0");
if (new RegExp("^(-|\\+)?(\\d+(\\.\\d{0," + (digst + 1) + "})?)\\d*$").test(value1)) {
let value1 = "0" + RegExp.$2, pm = RegExp.$1, a = RegExp.$3.length, b = true;
if (a == digst + 2) {
let a = value1.match(/\d/g);
if (parseInt(a[a.length - 1]) > 4) {
for (var i = a.length - 2; i >= 0; i--) {
a[i] = parseInt(a[i]) + 1;
if (a[i] == 10) {
a[i] = 0;
b = i != 1;
} else break;
}
}
value1 = a.join("").replace(new RegExp("(\\d+)(\\d{" + digst + "})\\d$"), "$1.$2");
}
if (b) value1 = value1.substring(1);
const newVal = (pm + value1).replace(/\.$/, "")
resolve(newVal)
}
})
}
范围随机数
/**
* 范围随机数 Promise
* @param {Number} start 起始的正整数字
* @param {Number} end 结束的正整数字
* @returns {Number} 范围里的随机数字 包含起始结束数字
* @example
* GetRandom(1, 10);
*/
export function GetRandom(start, end) {
return new Promise((resolve) => {
let newVal = 0
start > end ? [start, end] = [end, start] : [start, end] = [start, end]
if (start.toString().indexOf('.') == -1 && end.toString().indexOf('.') == -1) {
newVal = (Math.floor(Math.random() * (end - start + 1)) + start)
} else {
newVal = Number.parseFloat(Math.random() * (end - start) + start).toFixed(2)
}
resolve(newVal)
})
}
最大值取整
/**
* 最大值取整 Promise
* @param {Number} number 数字
* @returns {Number} 取整数字
* @example
* GetMaxNumCeil(2578); // 3000
*/
export function GetMaxNumCeil(num) {
return new Promise((resolve) => {
let maxA = 0
if (Array.isArray(num)) {
num = num.flat(Infinity)
num = Math.max.apply(null, num)
}
let numLength = num.toString().length - 1
let maxOnce = num.toString().slice(0, 1)
let maxAi = num.toString().slice(1, numLength + 1)
maxAi == 0 ? maxA = maxOnce : maxA = (maxOnce - (-1)).toString();
for (let i = 0; i < numLength; i++) {
maxA += i * 0
}
resolve(maxA)
})
}
数组去重
/**
* 数组去重 Promise
* @param {Array} arr 数组
* @param {String} keys [{}]时的取值字段,默认 'id'
* @param {Boolean} keepPrevOrNext 保留第一个查询成员或最后一个查询成员,默认 'true'第一个
* @returns {Array} 去重后的数组
* @example
* GetArrayUnique([1,1,2,3] || [{ id: 1 }, { id: 2 }, { id: 1 }, { id: 3 }], 'id', true);
*/
export function GetArrayUnique(arr, keys = 'id', keepPrevOrNext = true) {
return new Promise((resolve) => {
let newArr = []
const nbType = (n) => typeof n === 'number'
const obType = (n) => typeof n === 'object' && !Array.isArray(n)
if (arr.every((n) => nbType(n))) {
newArr = Array.from(new Set(arr))
} else if (arr.every((n) => obType(n))) {
for (let i = 0; i < arr.length; i++) {
const idx = newArr.findIndex((n) => n?.[keys] === arr[i][keys])
if (idx > -1) {
if (!keepPrevOrNext) {
newArr[idx] = arr[i]
}
continue
}
newArr.push(arr[i])
}
}
resolve(newArr)
})
}
获取数组出现次数最多的值
/**
* 获取数组出现次数最多的值 Promise
* @param {Array} arr 数组
* @returns {Object} 出现最多次数的值和出现的次数
* @example
* GetAppearMaxValue([1,1,2,3,4,4]);
*/
export function GetAppearMaxValue(arr) {
return new Promise((resolve) => {
let obj = {}
let maxNum = 0
const maxArr = []
const typeObj = Object.groupBy(arr, item => item)
for (let keys in typeObj) obj[keys] = typeObj[keys].length
for (let keys in obj) {
const item = obj[keys]
if (item > maxNum) {
maxNum = item
maxArr[0] = keys
} else if (maxNum === item) {
maxArr.push(keys)
}
}
resolve({ maxList: maxArr, maxNum })
})
}
执行顺序
// Promise || await Promise 按顺序
// Promise.then || await Promise.then
// setiTimeout || setInterval