小函数封装

205 阅读1分钟

随机生成字符串


/**
 * 随机生成字符串
 * @param length 字符串的长度
 * @param chats 可选字符串区间(只会生成传入的字符串中的字符)
 * @return string 生成的字符串
 */
 
export function randomString(length, chats) {
  if (!length) length = 1;
  if (!chats) chats = '0123456789qwertyuioplkjhgfdsazxcvbnm'
  let str = ''
  for (let i = 0; i < length; i++) {
    let num = randomNumber(0, chats.length - 1)
    str += chats[num]
  }
  return str
}

随机生成uuid

/**
 * 随机生成uuid
 * @return string 生成的uuid
 */
export function randomUUID() {
  let chats = '0123456789abcdef'
  return randomString(32, chats)
  
}

防抖

// 防抖
export function debounce(fn, delay) {
    var delay = delay || 200;
    var timer;
    return function () {
        var th = this;
        var args = arguments;
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(function () {
            timer = null;
            fn.apply(th, args);
        }, delay);
    };
}

节流

// 节流
export function throttle(func, wait) {
    let timeout;
    return function() {
        let context = this;
        let args = arguments;
        if (!timeout) {
            timeout = setTimeout(() => {
                timeout = null;
                func.apply(context, args)
            }, wait)
        }
    }
}

数组嵌套json 去重

/**
 * 数组嵌套json 去重
 * id 判断条件字段
 */
export function unRepeat(arr,id) {
  const res = new Map();
  return arr.filter((arr) => !res.has(arr[id]) && res.set(arr[id], 1))
}

unRepeat(arr,'id')

listToTree

export function listToTree(list, parent){
  const out = []
  for (let node of list) {
    if (node.pid == parent) {
      // 递归
      let children = listToTree(list, node.id)
      if (children.length) {
        node.children = children
      }
      out.push(node)
    }
  }
  return out
}

listToTree(this.cloneRightArr,0);

treeToArray

treeToArray 【扁平化数据】 treeToArray(data){ return data.reduce((res,{children = [], ...params}) => { return res.concat([params],treeToArray(children)) },[]) }