快排,节流,防抖,深拷贝

268 阅读1分钟
      //快排
     function qSort(arr){
       if(arr.length <= 1){
         return arr;
       }
       const leftArr=[];
       const rightArr=[];
      //用数组方法取出要排序的一个数
       const center = arr.shift();
       arr.forEach((item,index)=>{
         if(item<center){
           leftArr.push(item);
         }else{
           rightArr.push(item);
         }
       })
       const newArr = qSort(leftArr).concat(center,qSort(rightArr));
       return newArr;
     }
     const arr1 = [3,5,7,1,2];
     const re = qSort(arr1);
     console.log(re);
 <script>
    //节流
    function center(){
      //核心代码
      console.log(this);
    }
    document.onmousemove = throllted(center,500);
    function throllted(fn,time){
      let lastTime = 0;
      return function (){
        //获取时间戳来作为看门狗
        let nowTime = Date.now();
        //看门狗
        if(nowTime - lastTime < time){
          return;
        }
        lastTime= nowTime;
        fn.call(this,arguments[0]);
      }
    }
  </script>
<body>
  <input type="text" id="inp">
  <script>
    const inp =document.getElementById("inp");
    //核心代码
    function center(e){
      console.log(e);
      consoel.log(this);
    }
    inp.oninput =debounce(center,300);
    //封装一个防抖函数
    function debounce(fn,time){
      //初始化一个定时器
      let timer = null;
      return function () {
        clearTimeout(timer);
        var _this =this;
        var e = arguments[0];
        //使用定时器让代码延迟执行
        timer =setTimeout(function () {
          //控制核心函数的事件和对象
            fn.call(_this,e)
        }, time);
      }

    }
  </script>
</body>

``

 //深拷贝
    //判断数据类型
    function unType(data){
      return  Object.prototype.toString.call(data).slice(8.-1).toLowserCase();
    }
    function deepClone(data){
      if(data === "object"){
        var newObj ={};
      }else if(data === "array"){
        var newObj =[];
      }else{
        return data;
      }
      for(let key in data){
        newObj[key] = deepClone(data[key]);
      }
      return newObj;
    }