JS一些算法的总结

快速排序

const quickSort = (arr) => {
    const lth = arr.length;
    if (lth <= 1) {
        return arr;
    }
    const pivotIndex = Math.floor(lth / 2);
    const pivot = arr.splice(pivotIndex, 1)[0];
    const left = [];
    const right = [];
    for (let i = 0; i < arr.length; i++) {
        arr[i] < pivot ? left.push(arr[i]) : right.push(arr[i]);
    }
    return quickSort(left).concat([pivot], quickSort(right));
}
console.log(quickSort([1,2,6,3,5]));

深度拷贝

function deepClone(obj) {  
  function isClass(o) {    
  if (o === null) return "Null";    
  if (o === undefined) return "Undefined";    
    return Object.prototype.toString.call(o).slice(8, -1);  
  }  
  var result;  
  var oClass = isClass(obj);  
  if (oClass === "Object") {    
    result = {};  
  } else if (oClass === "Array") {
    result = [];  
  } else {    
    return obj;  
  }  
  for (var key in obj) {    
    var copy = obj[key];    
    if (isClass(copy) == "Object") {      
      result[key] = arguments.callee(copy);//递归调用    
    } else if (isClass(copy) == "Array") {      
      result[key] = arguments.callee(copy);    
    } else {      
      result[key] = obj[key];    
    }  
  }  
  return result;
}

深度拷贝-简单版

const deepCopy = (obj) => {
  if (typeof obj !== 'object') return;
  // 根据obj的类型判断是新建一个数组还是对象
  var newObj = obj instanceof Array ? [] : {};
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
    }
  }
  return newObj;
}

防抖

function debounce(func, wait) {
    let timeout;
    return function () {
        let context = this;
        let args = arguments;

        if (timeout) clearTimeout(timeout);
        
        timeout = setTimeout(() => {
            func.apply(context, args)
        }, wait);
    }
}

节流

function throttle(func, wait) {
    let previous = 0;
    return function() {
        let now = Date.now();
        let context = this;
        let args = arguments;
        if (now - previous > wait) {
            func.apply(context, args);
            previous = now;
        }
    }
}

持续更新中……

你可能感兴趣的:(JS一些算法的总结)