节流与防抖
function debounce(fn, wait) {
let timer = null
return function() {
let context = this
if(timer) {
clearTimeout(timer)
timer = null
}
timer = setTimeout(()=>{
fn.apply(context, arguments)
},wait)
}
}
function throttle(fn,wait) {
let flag = null
return function () {
if(flag) return
flag = setTimeout(()=>{
fn.apply(this,arguments)
},wait)
}
}
手写深拷贝
const isObj = (val) =>{
return typeof val === 'object' && val !== null
}
function deepClone (obj) {
const newObj = obj instanceof Array ? [] : {};
for (const key in obj) {
if (Object.hasOwnProperty.call(object, key)) {
const element = obj[key];
newObj[key] = isObj(element) ? deepClone(element) : element;
}
}
return newObj;
}
手写数组拍平方法
let arr = [1,2,[3,4,[5,6]]]
let a1 = arr.flat(Infinity)
console.log('flat拍平数组===》》',a1);
let str = JSON.stringify(arr).replace(/(\[|\])/g, '')
str = '[' + str + ']'
console.log(str);
function flat(arr) {
let result = []
for (const item of arr) {
item instanceof Array ? result = result.concat(flat(item)) : result.push(item)
}
return result
}
let a3 = flat(arr)
console.log('aeee3333333',a3);
手写call,apply,bind
Function.prototype.myCall= function(context, ...args) {
context = context || window
const key = Symbol()
context[key] = this
let result = context[key](...args)
delete context[key]
return result
}
Function.prototype.myApply = function (context, args=[]) {
context = context || window
const key = Symbol()
context[key] = this
let result = context[key](...args)
delete context[key]
return result
}
Function.prototype.myBind = function(context, ...args1) {
const self = this
return function(...args2) {
return self.apply(context, [...args1, ...args2])
}
}
手写instanceof
function myInstanceof(left,right) {
if(typeof left !=='object' || left === null) return false
let proto = Object.getPrototypeOf(left)
let prototype = right.prototype
while(true) {
if(!proto) {
return false
}
if(proto==prototype) {
return true
}
proto = Object.getPrototypeOf(proto)
}
}
手写new
function myNew(constructor, ...args) {
const newObj = {}
Object.setPrototypeOf(newObj, constructor.prototype);
const result = constructor.apply(newObj, args);
return typeof result === 'Object' && result !== null ? result : newObj;
}
手写promise
const PENDING = 'PENDING';
const FULTILLED = 'FULTILLED';
const REJECTED = 'REJECTED'
class Promise {
constructor(executor) {
this.status = PENDING;
this.value = undefined
this.reason = undefined
this.onResolvedCallbacks = []
this.onRejectedCallbacks = []
let resolve = (value) => {
if(this.status === PENDING) {
this.status = FULTILLED
this.value = value
this.onResolvedCallbacks.forEach(fn => fn())
}
}
let reject = (reason) => {
if(this.status === PENDING) {
this.status = REJECTED
this.reason = reason
this.onRejectedCallbacks.forEach(fn => fn())
}
}
try {
executor(resolve, reject)
} catch (error) {
reject(error)
}
}
then(onFulfilled, onRejected) {
if(this.status === FULTILLED) {
onFulfilled(this.value)
}
if(this.status === REJECTED) {
onRejected(this.reason)
}
if(this.status === PENDING) {
this.onRejectedCallbacks.push(() => {
onFulfilled(this.value)
})
this.onRejectedCallbacks.push(() => {
onRejected(this.reason)
})
}
}
}
static all(promises) {
let res = []
let count = 0
return new myPromise((resolve, reject) => {
if (!Array.isArray(promises)) {
return reject(new TypeError('Argument is not iterable'))
}
if (!promises.length) {
return resolve(res)
}
promises.forEach((item, index) => {
myPromise.resolve(item).then(val => {
count++
res[index] = val
count === promises.length && resolve(res)
}, reject)
})
})
}
const promise = new Promise((resolve, reject) => {
resolve('成功')
}).then((data)=> {
console.log('success', data);
},
(err) => {
console.log('error', err);
}
)
数组转树形结构
let list = [
{ "id": 12, "parent_id": 1, "name": "朝阳区" },
{ "id": 241, "parent_id": 24, "name": "田林街道" },
{ "id": 31, "parent_id": 3, "name": "广州市" },
{ "id": 13, "parent_id": 1, "name": "昌平区" },
{ "id": 2421, "parent_id": 242, "name": "上海科技绿洲" },
{ "id": 21, "parent_id": 2, "name": "静安区" },
{ "id": 242, "parent_id": 24, "name": "漕河泾街道" },
{ "id": 22, "parent_id": 2, "name": "黄浦区" },
{ "id": 11, "parent_id": 1, "name": "顺义区" },
{ "id": 2, "parent_id": 0, "name": "上海市" },
{ "id": 24, "parent_id": 2, "name": "徐汇区" },
{ "id": 1, "parent_id": 0, "name": "北京市" },
{ "id": 2422, "parent_id": 242, "name": "漕河泾开发区" },
{ "id": 32, "parent_id": 3, "name": "深圳市" },
{ "id": 33, "parent_id": 3, "name": "东莞市" },
{ "id": 3, "parent_id": 0, "name": "广东省" }
]
function treeing(arr) {
let tree = []
const map = {}
for (const item of arr) {
const id = item.id
const pid = item.parent_id
if (!map[id]) {
map[id] = {
children: [],
}
}
map[id] = {
...item,
children: map[id]['children']
}
const treeItem = map[id]
if(pid == 0) {
tree.push(treeItem)
}else {
if(!map[pid]) {
map[pid] = {
children:[]
}
}
map[pid].children.push(treeItem)
}
}
return tree
}