@df8080/vue2-ui
Version:
🎨 一个基于 Vue 2 的 UI 组件库,目前主要面向微信小程序开发场景,也适用于其他移动端项目。
104 lines (86 loc) • 2.69 kB
JavaScript
import { OPTION_VALUE, OPTION_LABEL } from '../config/constants'
import { isArray } from './is'
/**
* @description 数组去重
* @param list 列表数据
* @param key 判断重复的key,传数组是联合校验
* @return 去重结果
*/
export const uniqueArray = (list, keys) => {
const data = []
const map = new Map()
list.forEach((item) => {
const key = isArray(keys)
? keys.reduce((str, key) => `${str}${item[key]}`, '')
: `${item[keys]}`
if (!map.get(key)) {
map.set(key, true)
data.push(item)
}
})
return data
}
/**
* @description 时间范围拼接
* @param data 拼接的数据
* @param timeRange 时间范围的key值
*/
export const timeRangeFill = (data, timeRange) => {
const [start, end] = timeRange
if (Object.hasOwnProperty.call(data, start)) {
data[start] = data[start] && `${data[start]} 00:00:00`
}
if (Object.hasOwnProperty.call(data, end)) {
data[end] = data[end] && `${data[end]} 23:59:59`
}
}
/**
* @description 通过obj获取下拉选项
* @param obj 对象
* @return 下拉选项
*/
export const getOptionsByObj = (obj, options = {}) => {
const { value = OPTION_VALUE, label = OPTION_LABEL } = options
return Object.keys(obj).map((key) => ({ [value]: key, [label]: obj[key] }))
}
/**
* @description 通过映射获取下拉选项
* @param map 映射
* @return 下拉选项
*/
export const getOptionsByMap = (map, options = {}) => {
const { value = OPTION_VALUE, label = OPTION_LABEL } = options
return [...map.keys()].map((key) => ({ [value]: key, [label]: map.get(key) }))
}
/**
* @description 数字格式化
* @param value 需要格式化的值 decimalLength小数点位数
* @param options 格式化的选项
* @return 格式化后的值
*/
export const numberFormat = (value, options = {}) => {
const { decimalLength = 0, min = 0 } = options
value = String(value).replace(new RegExp(`[^0-9.${min < 0 ? '-' : ''}]`, 'g'), '')
const valSplit = value.split('.').slice(0, 2)
valSplit[0] = valSplit[0].slice(0, Number.MAX_SAFE_INTEGER.toString().length)
if (typeof valSplit[1] !== 'undefined' && decimalLength) {
valSplit[1] = valSplit[1].slice(0, decimalLength)
} else {
valSplit.splice(1, 1)
}
const formatVal = valSplit.join('.')
if (isNaN(+formatVal)) {
return min
}
return formatVal
}
/**
* @description 数字范围限制
* @param value 数值
* @param options 限制范围选项 min最小值 max最大值
* @return 限制后的值
*/
export const numberMinAndMax = (value, options = {}) => {
const { min = 0, max = Number.MAX_SAFE_INTEGER } = options
return Math.max(Math.min(max, value), min)
}