writerTitle


防抖

function Debounce(fn, timer) {
  var timeEvent;
  var arg = arguments;
  return function() {
    var that = this;
    // 判断是否有事件在执行,有的话,就停止执行下面语句
    if(timeEvent) return;
    timeEvent = setTimeout(function(){
      // ...arguments 获得事件对象
      fn.call(that, ...arg);
      clearTimeout(timeEvent);
    }, timer);
  }
}

节流

function Throttle(fn, timer) {
  var timeEvent;
  return function() {
    var that = this;
    var arg = arguments;
    if(timeEvent) {
      // 存在事件,清除掉,开始新的事件
      clearTimeout(timeEvent);
      timeEvent = setTimeout(function(){
      fn.call(that, ...arg);
      clearTimeout(timeEvent);
    }, timer);
    } else{
      timeEvent = setTimeout(function(){
        fn.call(that, ...arg);
        clearTimeout(timeEvent);
      }, timer);
    }
  }
}

深拷贝

function cloneDeep(data, map = new Map()) {
  // 初始化结果
  var result = Array.isArray(data) ? [] : {};
  if(typeof data === 'object') {
    // 防止引用,造成内存溢出
    map.set(data, 1);
    for(var key in data) {
      // 判断是否为引用,是的暂停拷贝;
      if(typeof data[key] === 'object') {
        if(map.has(data[key])) {
          result[key] = data[key];
          continue;
        }
        result[key] = cloneDeep(data[key], map);
      }else {
        Array.isArray(data) ? result.push(data[key]) : result[key] = data[key];
      }
    }
    return result;
  }
  return data;
}

数组转换成树

const data = [
{id: 1, parentId: 0},
{id: 2, parentId: 1},
{id: 3, parentId: 1},
{id: 4, parentId: 1},
{id: 5, parentId: 2},
{id: 6, parentId: 3},
{id: 7, parentId: 4},
{id: 8, parentId: 9},
]

function Tree(data) {
  const map = new Map();
  const result = [];
  data.forEach(item => {
    const child = data.filter(val => item.id === val.parentId);
    if(child.length !== 0) {
      child.map(val1 => {
        map.set(val1.id, val1);
      })
      item.children = child;
    } else {
      if(!map.has(item.id)) {
        result.push(item);
      }
    }
  })
  return [...result, data[0]];
 
}

Author: andelio
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source andelio !
  TOC