call
Function.prototype.myCall = function (context, ...args) {
context = context || globalThis
context.fn = this
const result = context.fn(...args)
delete context.fn
return result
}
apply
Function.prototype.myApply = function (context, args) {
context = context || globalThis;
context.fn = this;
const result = context.fn(...(args || []));
delete context.fn;
return result;
};
bind
Function.prototype.myBind = function (context, ...args) {
const fn = this;
return function (...args2) {
return fn.apply(context, [...args, ...args2]);
};
};
函数柯里化
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn(...args);
} else {
return function (...args2) {
return curried(...args, ...args2);
};
}
};
}
快速排序
function quickSort(arr) {
if (arr.length <= 1) {
return arr;
}
const pivot = arr[arr.length - 1];
const left = [];
const right = [];
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return [...quickSort(left), pivot, ...quickSort(right)];
}
浅拷贝
function shallowCopy(obj) {
if (typeof obj !== 'object' || typeof obj !== null) {
return obj
}
return Object.assign({}, obj)
}
深拷贝
function deepCopy(obj) {
let deepCloneObj = Array.isArray(obj) ? [] : {}
if (obj && typeof obj === 'object') {
for (let key in obj) {
console.log(key)
if (obj.hasOwnProperty(key)) {
deepCloneObj[key] = deepCopy(obj[key])
}
}
}
return deepCloneObj
}
解析url参数
function parseUrl(url) {
const result = {}
const params = url.split("?")[1]
const paramsArr = params.split("&")
paramsArr.forEach(item => {
const key = item.split("=")[0]
const value = item.split("=")[1]
result[key] = value
});
console.log(result)
}
递归
function factorial1(n) {
if (n === 1) return 1
return n * factorial(n - 1)
}
function factorial(n, total) {
if (n === 1) return total
return factorial(n - 1, n * total)
}
防抖、节流
function myDebounce(fn, wait) {
let timer;
return function () {
const context = this
const args = arguments;
if (timer) {
clearTimeout(timer)
timer = null
}
timer = setTimeout(() => {
fn.apply(context, args)
}, wait)
}
}
function myThrottle(fn, delay) {
let curTime = Date.now();
return function () {
const context = this;
const args = arguments;
nowTime = Date.now()
if (nowTime - curTime >= delay) {
curTime = Date.now();
return fn.apply(context, args)
}
}
}
将JS对象转化为树形结构
const items = [
{ id: 1, name: 'Item 1', parentId: null },
{ id: 2, name: 'Item 1.1', parentId: 1 },
{ id: 3, name: 'Item 1.2', parentId: 1 },
{ id: 4, name: 'Item 2', parentId: null },
{ id: 5, name: 'Item 2.1', parentId: 4 }
];
function buildTree(items, parentId = null) {
let tree = [];
for (let i in items) {
console.log('i--->', i)
if (items[i].parentId == parentId) {
const children = buildTree(items, items[i].id);
if (children.length) {
items[i].children = children;
}
tree.push(items[i]);
}
}
return tree;
}
const tree = buildTree(items);
console.log(tree);