前端开发常用公共函数

182 阅读4分钟

优雅的使用 setTimeout

通过 async、await 同步调用 setTimeout 定时器,改变传统的 setTimeout(() => {}, time) 调用方式

const fun = async() => {
    await timeout(1000)
    console.log(1)              // 一秒后执行打印
}

📄 代码

const timeout = time => new Promise(resolve => setTimeout(resolve, time))

🎗️ TypeScript

const timeout = (time: number) => new Promise<void>(resolve => setTimeout(resolve, time))

指定范围随机生成整数

指定一个数字范围,在范围内随机生成一个整数,包含起始数和结束数。

📄 代码

/**
 * @param {number} min 起始值
 * @param {number} max 结束值
 * @return {number} 随机数
 * */ 
const getRandomInt = (min, max) => Math.floor(Math.random() * (max - min) + 1) + min

🎗️ TypeScript

type GetRandomInt = (min: number, max: number) => number 

const getRandomInt: GetRandomInt = (min, max) => Math.floor(Math.random() * (max - min) + 1) + min

字符串裁剪

裁剪字符串长度,超出部分以省略号显示,一般用于裁剪表格行数据、卡片描述文本等。

cropText('HelloWorld', 5)            // Hello...

📄 代码

/**
 * @param {string} text 需要裁剪的字符串
 * @param {number} length 需要保留的长度
 * @return {string} 裁剪后字符串
 * */ 
const cropText = (text, length) => text.length >= length ? `${text.substring(0, length)}...` : text 

🎗️ TypeScript

type CropText = (text: string, length: number) => string 

const cropText: CropText = (text, length) => text.length >= length ? `${text.substring(0, length)}...` : text } 

解析 URL 地址参数

将 URL 中通过 &# 携带的参数解析为对象

const url = 'https://mail.163.com/js6/main?id=1001&address=china#module=javsscript'
analysisURLParams(url)         // { id: '1001', address: 'china', module: 'javsscript' }

📄 代码

/** 
 * @param {string} url 需要解析的地址 
 * @return {object} 参数对象
 * */
const analysisURLParams = url => {  
    const paramsObj = {}  
    // 截取 ? 后的字符串,即参数  
    const urlParams = url.split('?')[1]  
    // 判断是否有参数  
    if (urlParams) {  
        // 通过 & 分割参数  
        const paramsArr = urlParams.split('&')  
        paramsArr.forEach((item, index) => {  
            // 判断字符串中是否存在 # , 如果存在则分割并添加到数组中  
            if (item.includes('#')) paramsArr.splice(index, 1, ...item.split('#'))  
        })  
        paramsArr.forEach(item => {  
            const [key, value] = item.split('=')  
            paramsObj[key] = value  
        })  
    }  
    return paramsObj  
}  

🎗️ TypeScript

type AnalysisURLParams = (url: string) => Record<string, any> 

const analysisURLParams: AnalysisURLParams = url => { 
    const paramsObj: Record<string, string> = {} 
    const urlParams = url.split('?')[1] 
    if (urlParams) { 
        const paramsArr: string[] = urlParams.split('&') 
        paramsArr.forEach((item, index) => { 
            if (item.includes('#')) paramsArr.splice(index, 1, ...item.split('#'))
        }) 
        paramsArr.forEach(item => { 
            const [key, value] = item.split('=') 
            paramsObj[key] = value 
        }) 
    } 
    return paramsObj 
} 

获取/排除 对象部分属性创建新对象

获取或排除一个对象中的指定属性,并以一个新对象的形式返回

const obj = {  
    a: true,  
    b: 1,  
    c: 'str',  
    d: null,  
    e: undefined,  
    f: /[1-9]?/  
}

// 获取 a, c, e
deconstructObj(obj, ['a', 'c', 'e'])              // { a: true, c: 'str', e: undefined }

// 排除 a, c, e
deconstructObj(obj, ['a', 'c', 'e'], false)       // { b: 1, d: null, f: /[1-9]?/ }

📄 代码

/**  
* @param {object} obj 需要传入的对象  
* @param {array} keyArr 需要处理的对象属性  
* @param {boolean} isGet 获取属性 true [默认值] / 排除属性 false  
* @return {object} 新对象   
* */  
const deconstructObj = (obj, keyArr, isGet = true) => {  
    const result = {}  
    for(const [key, value] of Object.entries(obj)) {  
        if (isGet ? keyArr.includes(key) : !keyArr.includes(key)) result[key] = value  
    }  
    return result  
}  

🎗️ TypeScript

type DeconstructObj = (obj: object, keyArr: string[], isGet?: boolean) => object  
  
const deconstructObj: DeconstructObj = (obj, keyArr, isGet: boolean = true) => {  
    const result: Record<string, any> = {}  
    for (const [key, value] of Object.entries(obj)) {  
        if (isGet ? keyArr.includes(key) : !keyArr.includes(key)) result[key] = value  
    }  
    return result  
}  
  
export default deconstructObj 

判断对象是否为空

通过判断对象属性长度实现,返回布尔值 空对象 true、非空对象 false

objectIsNull({})                           // true
objectIsNull({ name: '张三' })             // false

📄 代码

/**  
* @param {object} obj 需要判断的对象  
* @return {boolean} 空对象 true、非空对象 false
* */
const objectIsNull = obj => !Object.keys(obj).length

🎗️ TypeScript

const objectIsNull = (obj: object): boolean => !Object.keys(obj).length

判断数据类型

通过 callObjcet.prototype.toString() 指向指定的数据,直接返回具体的数据类型

judgeDataType(1)                               // number
judgeDataType('str')                           // string
judgeDataType(undefined)                       // undefined
judgeDataType({})                              // object

📄 代码

/**  
* @param {any} data 数据
* @return {string} 数据类型
* */
const judgeDataType = data => Object.prototype.toString.call(data).slice(8, -1).toLowerCase()

🎗️ TypeScript

type DataType = 'string' | 'boolean' | 'number' | 'null' | 'undefined' |  
                'symbol' | 'object' | 'array' | 'date' | 'regexp' | 'function'  

const judgeDataType = (data: any) => <DataType>Object.prototype.toString.call(data).slice(8, -1).toLowerCase()

获取某个月的天数

// 不指定月份,获取当前月
getDaysNum()       

// 指定月份
getDaysNum(1)                                  // 31
getDaysNum(12)                                 // 31

📄 代码

/**  
* @param {number} month 月份,默认为当前月
* @return {number} 天数
* */
const getDaysNum = (month = new Date().getMonth() + 1) => new Date(new Date().getFullYear(), month, 0).getDate()

🎗️ TypeScript

type GetDaysNum = (month: number) => number

const getDaysNum: GetDaysNum = (month = new Date().getMonth() + 1) => new Date(new Date().getFullYear(), month, 0).getDate()

自定义打印颜色

有时控制台打印信息过多不容易辨别,而带有颜色的打印信息将有利于区分信息,对于引用类型数据只能打印出JSON.stringify() 转换之后的值

Log.primary(1)  
Log.success({ name: '张三', age: 20})  
Log.warning('str')  
Log.danger([1, 2, 3])

2023-06-10_231258.png

📄 代码

const consoleLog = (content, color) => {  
    const logContent = typeof content === 'object' ? JSON.stringify(content) : content  
    console.log(`%c${logContent}`, `color: ${color}`)  
}  
  
// 预定义颜色  
const Log = {  
    primary(content) {  
        consoleLog(content, '#409EFF')  
    },  
    success(content) {  
        consoleLog(content, '#67C23A')  
    },  
    warning(content) {  
        consoleLog(content, '#E6A23C')  
    },  
    danger(content) {  
        consoleLog(content, '#F56C6C')  
    }  
}

🎗️ TypeScript

type LogInfo = (content: any, color?: string) => void  
type LogType = 'primary' | 'success' | 'warning' | 'danger'  
type LogFun = Record<LogType, LogInfo>  
  
const consoleLog: LogInfo = (content, color) => {  
    const logContent = typeof content === 'object' ? JSON.stringify(content) : content  
    console.log(`%c${logContent}`, `color: ${color}`)  
}  
  
// 预定义颜色  
const Log: LogFun = {  
    primary: content => consoleLog(content, '#409EFF'),  
    success: content => consoleLog(content, '#67C23A'),  
    warning: content => consoleLog(content, '#E6A23C'),  
    danger: content => consoleLog(content, '#F56C6C')  
}