手写代码

45 阅读2分钟

柯里化的手写

实现1:

function curry(fn){
    
    const innerFunction =( args = [])=> args.length >= fn.length ? fn(...args) : (...userargs)=> innerFunction([...args,...userargs])
    return innerFunction()
}

实现2:

function curry(fn){
 const inner = (args = [])=> args.length >= fn.length ? fn(...args) : (...userargs)=> inner([...args,...userargs])
}
return inner()

实现3:


function Currying(fn) {
  const function curried(...args){
      if(args.length>=fn.length){
      return fn.call(this,...args)
      }  else{
          return fnuction(...userargs){
              return curried.apply(this,[...args,...userargs])
          }
      }
  }
}

自定义事件总线

发布订阅模式 核心就是把多个方法先暂存起来,最后一次执行
class MyEventBus{
    constructor() {
        this.eventBus = {}
    }
    
    on(eventName,eventCallback,thisArg){
        let handlers = this.eventBus[eventName]
        if (!handlers){
            handlers=[]
            this.eventBus[eventName]= handlers
        }
        handlers.push({eventCallback,thisArg})
    }
    emit(eventName,...payload){
        let handlers=this.eventBus[eventName]
        if (!handlers){
            return;
        }else {
            debugger
            handlers.forEach(item=>item.eventCallback.apply(item.thisArg,payload) )
        }
    }
}


let eventBus =new MyEventBus()

obj={a:3333}

eventBus.on("myfirst",function (data="ssssss"){

    console.log(data);
    console.log(this.a);
    },obj
)

setTimeout(()=>{
    eventBus.emit("myfirst","2222222")
},2000)

//2222222
//3333

观察者模式

核心是 被观察者 收集 观察者 ,然后 被观察者状态改变时通知 观察者(调用收集的观察者的对象的某个函数) 让观察者执行某项操作

class Observed{ //被观察者
    constructor(name) {
    //
        this.name=name;
        this.observers=[]
        this.state='非常开心'
    }
    attach(o){ //  小宝宝 进行收集
        this.observers.push(o); // on
    }
    setState(state){
        this.state=state
        this.observers.forEach(o=>{
            o.update(this.name,this.state)
        })
    }
}
class Observer{
    constructor(name) {
        this.name=name
    }
    update(name,state){
        console.log(this.name+":" + name + '当前'+state)
    }
}
let s = new Observed('小宝宝');
let o1 = new Observer('爸爸');
let o2 = new Observer('妈妈');
s.attach(o1)
s.attach(o2)
s.setState('不开心了')
s.setState('开心了')

Promise 的基本实现

const PROMISE_STATUS_PENDING = 'pending'
const PROMISE_STATUS_FULFILLED = 'fulfilled'
const PROMISE_STATUS_REJECTED = 'rejected'
class MyPromise{
    constructor(executor) {
        debugger
        this.status = PROMISE_STATUS_PENDING

        this.value=''
        this.reason=''
        const resolve=(value)=>{
            if (this.status===PROMISE_STATUS_PENDING){
                this.status=PROMISE_STATUS_FULFILLED
                console.log("resolve")
                this.value=value
                //不加异步api的话,this.onFulfilled(this.value)就会在使用then之前调用,那么这时this.onFulfilled还不是一个方法
                queueMicrotask(()=>{
                    this.onFulfilled(this.value)
                })
            }
        }
        const reject =(reason)=>{
            if (this.status===PROMISE_STATUS_PENDING){
                this.status=PROMISE_STATUS_REJECTED
                console.log("reject")
                this.reason=reason
                queueMicrotask(()=>{
                    this.onRejected(this.reason)
                })

            }
        }
        executor(resolve,reject)
    }
    then(onFulfilled, onRejected) {
        debugger
        this.onFulfilled = onFulfilled
        this.onRejected = onRejected
    }
}


deepClone(深拷贝的写法)

function deepClone(obj,hash = new WeakMap()){// vue3  记录拷贝前和拷贝后的对应关系 
    if(obj == null) return obj;
    if(obj instanceof RegExp) return new RegExp(obj);
    if(obj instanceof Date) return new Date(obj);
    // .... 其他类型 可以类似的写法
    if(typeof obj !== 'object') return obj;
    // 对象类型 obj  数组 :[] 和 对象: {}

    if(hash.has(obj)) return hash.get(obj); // 返回上次拷贝的结果 不在递归了

    const copy = new obj.constructor;
    hash.set(obj,copy); // 引用类型 
    for(let key in obj){
        if(obj.hasOwnProperty(key)){
            copy[key] = deepClone(obj[key],hash)
        }
    }
    return copy
}