手写深拷贝
export function deepClone(obj, hash = new WeakMap()) {
if (obj === null) return obj;
if (obj instanceof Date) return new Date(obj);
if (obj instanceof RegExp) return new RegExp(obj);
if (typeof obj !== "object") return obj;
if (hash.get(obj)) return hash.get(obj);
let cloneObj = new obj.constructor();
hash.set(obj, cloneObj);
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
cloneObj[key] = deepClone(obj[key], hash);
}
}
return cloneObj;
}
手写new
function myNew (fun,...args){
if(typeof fun !== 'function') {
throw Error('只能是函数')
}
const obj = {}
obj.__proto__ = Object.create(fun.prototype)
const res = fun.call(obj,...args)
if(typeof res === 'object') return res
return obj
}
手写防抖
function debounce(fun,delay){
let timer = ''
return function(){
if(timer){
clearTimeout(timer)
}
timer = setTimeout(()=>{
fun.apply(this,arguments)
timer = null
},delay)
}
}
手写节流 定时器版本
function throttle(fn,interval){
let timer = ''
return function () {
if(timer){
return
}
timer = setTimeout(()=>{
fn.apply(this,arguments)
clearTimeout(timer)
timer = null
},interval)
}
}
手写call
Function.prototype.myCall = function(context,args){
const context = context || window
const key = Symbol('key')
context[key] = this
const res = context[key](args)
delete context[key]
return res
}
数组转树 非递归方式
function arrToTree(data) {
const result = []
const map = data.reduce((pre, cur) => {
pre[cur[id]] = {
...cur,
children: []
}
return pre
}, {})
for (const item of data) {
const newItem = map[item.id]
if (map[item.pId]) {
map[item.pId].children.push(newItem)
} else {
result.push(newItem)
}
}
return result
}
扁平化树 reduce 加递归实现
const tree = [
{
id:1,
label:1,
children:[{
id:11,
label:11
},{
id:12,
label:12
}]
}
]
function flat(tree){
return tree.reduce((v,c)=>{
const {children,...item} = c
return children?.length ? v.concat(item,flat(children)) : v.concat(item)
}, [])
}