快速排序
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);//遞歸調(diào)用
} 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;
// 根據(jù)obj的類型判斷是新建一個(gè)數(shù)組還是對(duì)象
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);
}
}
節(jié)流
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;
}
}
}
持續(xù)更新中……