通用
import get from 'lodash.get'
import cloneDeep from 'lodash.clonedeep'
export function deepClone(obj) {return obj ? cloneDeep(obj) : obj
}
export function lodashGet(obj, key, defaultValue = '') {return get(obj, key, defaultValue);
}
export const createUuid = (len, radix) => {var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')var uuid = []var iradix = radix || chars.lengthif (len) {for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]} else {var ruuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'uuid[14] = '4'for (i = 0; i < 36; i++) {if (!uuid[i]) {r = 0 | Math.random() * 16uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]}}}return uuid.join('')
}
export function getDataType(data) {if (data === null) {return 'null';}if (data instanceof Array) {return 'Array';}if (data instanceof Object) {return 'Object';}return 'param is no object type';
}
export function treeTraversal(treeList) {let list = [];const loop = (tree) => {tree.map((item) => {const children = item.children ? item.children : '';delete item.children;list = [...list, item];return children ? loop(children) : '';});};loop(deepClone(treeList));return list;
}
export function findFiled(val, filed, data = []) {if (!val) {return '';}const list = data[0] && data[0].children ? treeTraversal(data) : data;const nameArr = list.filter(({ dbid }) => dbid === val);if (!nameArr.length) {return '';}return lodashGet(nameArr[0], filed);
}
export function setQueryString(val) {let querystring = JSON.parse(localStorage.getItem('queryString'))querystring = querystring || {}const { query, hash } = router.app.$routeconst { name } = router.currentRouteconst newQuery = { ...query, ...val }querystring[name] = newQuerylocalStorage.setItem('queryString', JSON.stringify(querystring))router.replace({ query: newQuery, hash })
}
export function getQueryString(data) {const { currentRoute, app } = router;const { name } = currentRoute;const val = deepClone(data);const { query } = app.$route;const queryKeys = Object.keys(query);if (queryKeys.length) {Object.keys(val).forEach((key) => {if (queryKeys.find(queryKey => queryKey === key)) {const item = query[key];if (getDataType(val[key]) === 'Array' && getDataType(item) !== 'Array') {val[key] = !item ? [] : [item];} else if (item === 'true') {val[key] = true;} else if (item === 'false') {val[key] = false;} else if (item) {val[key] = item;}}});return JSON.parse(JSON.stringify(val), (k, v) => {v = v && typeof v === 'string' && !Number.isNaN(Number(v)) ? Number(v) : v;return v;});}return val;
}
export function isLight(color) {if (!color) {return false;}const colorRgb = () => {const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;color = color.toLowerCase();if (reg.test(color)) {if (color.length === 4) {let colorNew = '#';for (let i = 1; i < 4; i += 1) {colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));}color = colorNew;}const colorChange = [];for (let i = 1; i < 7; i += 2) {colorChange.push(parseInt(`0x${color.slice(i, i + 2)}`, 0));}return colorChange;}const list = [];color.replace(/[0-9]*(\.[0-9]*)?/g, (e) => {if (e !== '') {list.push(Number(e));}});return list;};const [r, g, b] = colorRgb();return r * 0.299 + g * 0.578 + b * 0.114 >= 192;
}export function grouping(data, key, groupType = 'Array', objModel = 'model1') {const newArray = []data.map((item) => [item]).forEach(([{ ...item }]) => {const flag = newArray.find(([{ ...o }]) => xeGet(o, key) === xeGet(item, key))if (!flag) {newArray.push([{ ...item }])} else {newArray.forEach(([{ ...y }], index) => {if (xeGet(y, key) === xeGet(item, key)) {newArray[index].push(item)}})}})if (groupType !== 'Array') {const ObjArray = []newArray.forEach((item) => {const obj = {}obj.groupName = xeGet(item[0], key)if (objModel === 'model1') {obj.valueList = item} else {obj.valueList = item.map((item) => item.y)}ObjArray.push(obj)})return ObjArray}return newArray
}
export function bytesUnitTransfer(bytes) {if (bytes) {if (String(bytes) === '0') return '0 B'const k = 1024const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']const i = Math.floor(Math.log(bytes) / Math.log(k))if (isNaN(i)) {return '-'} else {return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]}} else {return '-'}
}function getDigit(integer) {let digit = -1while (integer >= 1) {digit++integer = integer / 10}return digit
}
function addWan(integer, number, mutiple, decimalDigit) {const digit = getDigit(integer)if (digit > 3) {var remainder = digit % 8if (remainder >= 5) {remainder = 4}return Math.round(number / Math.pow(10, remainder + mutiple - decimalDigit)) / Math.pow(10, decimalDigit) + '万'} else {return Math.round(number / Math.pow(10, mutiple - decimalDigit)) / Math.pow(10, decimalDigit)}
}
export function numberUnitTransfer(number, decimalDigit) {decimalDigit = decimalDigit == null ? 2 : decimalDigitconst integer = Math.floor(number)const digit = getDigit(integer)const unit = []if (digit > 3) {var multiple = Math.floor(digit / 8)if (multiple >= 1) {const tmp = Math.round(integer / Math.pow(10, 8 * multiple))unit.push(addWan(tmp, number, 8 * multiple, decimalDigit))for (let i = 0; i < multiple; i++) {unit.push('亿')}return unit.join('')} else {return addWan(integer, number, 0, decimalDigit)}} else {return number}
}
export const numRevise = (num, type) => {if (!isNull(num) && !isNaN(num)) {if (isNull(type)) {return parseInt(num)}if (type === 'ceil' || type === 'floor' || type === 'round') {return Math[type](num)}}return undefined
}
文件处理
export const getImgWidthAndH = function (file) {return new Promise((resolve, reject) => {const reader = new FileReader()reader.readAsDataURL(file)reader.onload = function (event) {const base64 = event.target.resultconst img = new Image()img.src = base64img.onload = function () {resolve({ width: img.width, height: img.height })}}})
}
export function getBase64(file) {return new Promise(function (resolve, reject) {const reader = new FileReader()let imgResult = ''reader.readAsDataURL(file)reader.onload = function () {imgResult = reader.result}reader.onerror = function (error) {reject(error)}reader.onloadend = function () {resolve(imgResult)}})
}
export function getBase64ToUrl(base64) {const changebase64 = 'data:image/jpg;base64,' + base64.replace(/[\r\n]/g, '')return changebase64
}
export function blobToFile(res, fileName, type = 'application/vnd.ms-excel') {const link = document.createElement('a')const blob = new Blob([res.data], {type})link.style.display = 'none'link.href = URL.createObjectURL(blob)if (fileName) {link.download = fileName } else {link.download = res.headers['content-disposition']const name = decodeURI(escape(link.download.split('=')[1])) link.download = name }document.body.appendChild(link)link.click()document.body.removeChild(link)
}
export const getFileMIME = file => new Promise((resolve) => {const reader = new FileReader()reader.readAsArrayBuffer(file)reader.onload = (e) => {const typeHex = (new Uint8Array(reader.result)).subarray(0, 4).reduce((str, index) => str + index.toString(16), '').toLowerCase()resolve(typeHex ? FILE_MIME_HEX[typeHex] : '')}
})
tree合集
export function getChildren(val, tree, key = 'dbid') {let hasFound = false; let result = null;const fn = (data) => {if (Array.isArray(data) && !hasFound) {data.forEach((item) => {if (item[key] === val) {result = item; hasFound = true; } else if (item.children) {fn(item.children); }});}};fn(tree); return result;
}
export function getTrajectory(dataList) {let treePath = '';dataList.forEach(item => (treePath = `${treePath}/${item.nameZh}`));return treePath.substring(1);
}
export function getAllLeafNode(tree, key = 'dbid') {const val = [];const mapTree = (node, innerVal, innerKey) => {node.forEach((item) => {if (!item.children) {innerVal.push(item[innerKey]);} else {mapTree(item.children, innerVal, innerKey);}});};mapTree(tree, val, key);return val;
}
export function getTreeAppointField(tree, key = 'dbid') {const val = [];const mapTree = (node, innerVal, innerKey) => {node.forEach((item) => {innerVal.push(item[innerKey]);if (item.children) {mapTree(item.children, innerVal, innerKey);}});};mapTree(tree, val, key);return val;
}
export function treeTraversalToAdd(treeList, newData, uuid = true, childrenField = 'children') {const addKey = (arr) => {if (uuid) {return arr?.map((item) => ({uuid: createUuid(),...item,...newData,[childrenField]: item[childrenField] ? addKey(item[childrenField]) : []}))}return arr?.map((item) => ({...item,...newData,[childrenField]: item[childrenField] ? addKey(item[childrenField]) : []}))}const newTree = addKey(deepClone(treeList))return newTree
}export function addTreeChildren(val, tree, newData = {}, type = 'level', key = 'aid', first = false) {const newTree = deepClone(tree)let hasFound = false const traversal = data => {for (let i = 0; i < data.length; i++) {if (hasFound) returnconst info = data[i]if (lodashGet(info, key) !== val && info.children) {traversal(info.children)} else if (lodashGet(info, key) === val) {hasFound = true const index = data.findIndex(item => val === lodashGet(item, key))if (type === 'level') {if (first) {data.splice(index, 0, newData)return}data.splice(index + 1, 0, newData)} else {const dealData = { ...data[index], children: [newData, ...data[index]?.children] }data.splice(index, 1, dealData)}}}}traversal(newTree)return newTree
}
export function delTreeChildren(val, tree, key = 'aid') {const newTree = deepClone(tree)const traversal = data => {for (let i = 0; i < data.length; i++) {const info = data[i]if (lodashGet(info, key) !== val && info.children) {traversal(info.children)} else if (lodashGet(info, key) === val) {const index = data.findIndex(item => val === item[key])data.splice(index, 1)i--}}}traversal(newTree)return newTree
}
时间处理合集(moment.js)
export function formatTime(timeStr, format = 'YYYY-MM-DDTHH:mm:ss.SSSZ') {const getFormatString = () => {switch (format) {case 'yyyy-MM-dd':case 'YYYY-MM-dd':return 'YYYY-MM-DD';case 'yyyy-MM-dd HH:mm:ss':case 'YYYY-MM-dd HH:mm:ss':return 'YYYY-MM-DDTHH:mm:ss.SSSZ';default:return format;}};if (!timeStr) {return '';} if (timeStr[0] && timeStr[1]) {return [moment(timeStr[0]).format(getFormatString()), moment(timeStr[1]).format(getFormatString())];}return moment(timeStr).format(getFormatString());
}
export function subtractCurrentTime(amount = 1, unit = 'weeks') {return [formatTime(moment().subtract(amount, unit)), formatTime(moment())];
}
export function getDatePreAndNext(amount = 1, unit = 'weeks', data = '', type = 1) {const date = !data? moment().format('YYYY-MM-DD'): moment(data).format('YYYY-MM-DD')if (type === 0) {return [formatTime(moment(date).subtract(amount, unit)), formatTime(moment(`${date} 23:59:59`))]} if (type === 1) {return [formatTime(moment(date)), formatTime(moment(`${date} 23:59:59`).add(amount, unit))]}return [formatTime(moment(currentDate).subtract(amount, unit)),formatTime(moment(`${currentDate} 23:59:59`).add(amount, unit))]
}
export function getTimeByDate(amount = 2, unit = 'Hours', date = new Date()) {const dDate = date || new Date();const currentDate = moment(dDate).format('YYYY-MM-DD HH:mm:ss');return formatTime(moment(currentDate).add(amount, unit));
}
export function subtractStartAndEnd(amount = 1, unit = 'weeks') {const [startDate, endDate] = subtractCurrentTime(amount, unit);return [formatTime(moment(startDate).startOf(unit)), formatTime(moment(endDate).endOf(unit))];
}
export function subtractPreAndNext(amount = 1, unit = 'months', format = 'YYYY-MM-DD HH:mm:ss') {const date = moment().format('YYYY-MM-DD');if (Array.isArray(amount)) {return [formatTime(moment(date).subtract(amount[0], unit), format),formatTime(moment(`${date} 23:59:59`).add(amount[1], unit), format),];}return [formatTime(moment(date).subtract(amount, unit)), formatTime(moment(`${date} 23:59:59`).add(amount, unit))];
}
export function enumerateDaysBetweenDates(startDate, endDate) {const dates = [];const currDate = moment(startDate).startOf('day');const lastDate = moment(endDate).startOf('day');while (currDate.add(1, 'days').diff(lastDate) < 0) {dates.push(currDate.clone().toDate());}const { length } = dates;const i = Math.ceil(length / 2 - 1);return formatTime(dates[i]);
}
export function durationTime(startTime, endTime, unit = 'minute') {if (!startTime || !endTime) {return '';}const startDate = timeFormat(startTime);const seconds = moment(endTime, 'YYYY-MM-DD HH:mm:ss').diff(startDate, 'seconds');let duration = '';switch (unit) {case 'minute':duration = `${seconds / 60} 分钟`;break;case 'hours':duration = `${seconds / 2600} 小时`;break;default:break;}return duration;
}
export function dateStartAndEnd(unit = 'month', date = new Date(), format = 'YYYY-MM-DDTHH:mm:ss.SSSZ') {const currentDate = moment(date).format('YYYY-MM-DD');return [formatTime(moment(currentDate).startOf(unit), format), formatTime(moment(currentDate).endOf(unit), format)];
}
export function monthStartAndSameDay() {const date = moment().format('YYYY-MM-DD');return [formatTime(moment().startOf('month')), formatTime(moment(`${date} 23:59:59`))];
}
export function getStandardIntervalString(unit = 'month', date = undefined) {switch (unit) {case 'day': {return moment(date).format('YYYYMMDD');}case 'month': {return moment(date).format('YYYYMM');}case 'year': {return moment(date).format('YYYY');}}
}
数组操作
export const getArrayUnique = function (arr, key) {const newArrId = []const newArrObj = []arr.forEach((item) => {if (!newArrId.includes(item[key])) {newArrId.push(item[key])newArrObj.push(item)}})return newArrObj
}
export const getArrayDifference = function (arr1, arr2, key) {const result = []for (let i = 0; i < arr2.length; i++) {const obj = arr2[i]const unique1 = obj[key]let isExist = falsefor (let j = 0; j < arr1.length; j++) {const aj = arr1[j]const unique2 = aj[key]if (unique2 === unique1) {isExist = truebreak}}if (!isExist) {result.push(obj)}}return result
}
export function arrayToTree(arr) {const map = {}const result = []let nodefor (let i = 0; i < arr.length; i++) {map[arr[i].id] = arr[i]arr[i].children = []}for (let i = 0; i < arr.length; i++) {node = arr[i]if (node.parentId) {map[node.parentId].children.push(node)} else {result.push(node)}}return result
}
export function sortBy(props, type) {return function (a, b) {if (type === 'ascend') {return b[props] - a[props]} else if (type === 'descend') {return a[props] - b[props]}}
}