偷懒的代码片段

141 阅读2分钟

1.随机码生成

function useRandomCode(){
   // 记录对象
   const map = {}
   // 随机码生成函数
   const random = ()=> Math.random().toString(36).substring(2)
   return function(){
       let code = null
       // 死循环
       while(true){
           // 生出一个随机码
           code = random()
           // 校验是否重复
           if(!map[code]){
               // 如果未重复记录本次的随机码
               map[code] = 1
               // 然后返回
               return code
           }
       }
   }
}

const getRandom = useRandomCode()

getRandom()// => 反复调用输出理论不重复的字符串

2.深层对象安全读取

cosnt a = {}
const b = {a:{a:{}}}
console.log(a.a.a) // => 运行时会报错
console.log(b.a.a) // => 输出一个对象

// 函数接受两个参数 一个是需要被读取的源可以是任意类型 一个是读取路径 接收字符串
// 方法接受到参数后
const readLink = (target,links)=> links.split('.').reduce((res,key)=>{
    if([null,undefined].includes(res)){
        return undefined
    }
    return res[key]
},target)
console.log(readLink(a,'a.a')) // => 返回 undefined
console.log(readLink(b,'a.a')) // => 返回 {}
console.log(a?.a?.a) // => 新特性的写法

3.数组mock

// 根据length创建等长的数组,使用fill覆盖让数组的生成索引,最后使用map构建新的字段
const mockArr = (length,fill)=> new Array(length || 0).fill('').map((...arg)=>{
    return typeof fill =='function' ? fill(...arg) : fill
})
mockArr(5,1)// => [1,1,1,1,1]
mockArr(5,(_,i)=>i) // => [0,1,2,3,4]

4.状态记录

适用于状态为布尔值并且不能补充key的场景(除非后端需要否则我不喜欢额外增加key来决定数据的布尔状态)

    // 内置用来记录的数组
   let list = []
   // 判断是否存在内置数组内
   const isOn = item => list.includes(item)
   // 选中状态
   const on = item => {
       switch(true){
           // 已经选过了跳过
           case isOn(item):
               return
           // 没有选择上线控制直接推入
           case !maxOn:
               list.push(item)
               break
           // 如果有上限控制并且没到上限那么推入
           case maxOn > list.length:
               list.push(item)
               break
       }
   }
   // 取消状态
   const off = item => {
       // concat 用来支持数组和单个对象的处理(应该不会有人拿数组当一条数据吧- -)
       const items = [].concat(item)
       // 过滤传入的内容
       list = list.filter(el=> !items.includes(el))
   }
   // 状态切换
   const toggle = item =>{
       const items = [].concat(item)
       const offList = []
       items.forEach(el=>{
            // 如果已被选中记录到清除的清单中 否则 推入数组变成选中状态
           if(isOn(el)){
               offList.push(el)
           }else{
               list.push(el)
           }
       })
       // 有需要取消的调用 off 统一取消
       if(offList.length){
           off(offList)
       }

   }
   // 归0
   const clear = () => list = []

   return {
       on,
       off,
       toggle,
       clear,
       isOn,
       getOn: () => [...list],
   }
}

5.快速过滤指定属性

注意key不能包含 ':'

const filterKeys = (target, keys) => {
   const base = {} // 初始值
   return keys.reduce((res, cur) => {
       // 切割:进行重命名
       const [key, newKey = key] = cur.split(':')
       res[newKey] = target[key]
       return res
   }, base)
}
filterKeys({a:1,b:2,c:'',d:''},['a','b:vqdgqxcq']) // => {a:1,vqdgqxcq:2}