发布订阅和深拷贝


// 发布订阅,支持先订阅后发布和先发布后订阅
class EventEmitter {
  status = {}; // 状态 map
  value = {}; // 值map
  eventMap = {}; // 事件map
  on(task, fn) {
    if (!this.eventMap[task]) {
      this.eventMap[task] = [];
    }

    if(!this.status[task]) {
      this.status[task] = "pending"
    }

    if (this.status[task] === "pending") {
      this.eventMap[task].push(fn);
    }
    if (this.status[task] === "fulfilled") {
      fn(this.value[task]);
    }
  }

  emit(task, value) {
    if (!this.eventMap[task]) {
      this.eventMap[task] = [];
    }
    if(!this.status[task]) {
      this.status[task] = "pending"
    }

    this.status[task] = "fulfilled";
    if (!this.value[task]) {
      this.value[task] = value;
    }

    while (this.eventMap[task].length > 0) {
      let current = this.eventMap[task].shift();
      current(value);
    }
    
  }
}

const event1 = new EventEmitter();

const task1 = (res) => { console.log("res 1 :>> ", res); };
const task2 = (res) => { console.log("res 2 :>> ", res); };
const task3 = (res) => { console.log("res 3 :>> ", res); };

// event1.emit("task", Math.random());
event1.on("task", task1);
event1.on("task", task2);
event1.on("task", task3);
event1.emit("task", Math.random());



// 深拷贝
function deepClone(obj, cache = new WeakMap()){
  if(obj === null || typeof obj !== 'object') return obj;
  if(obj instanceof Date) return new Date(obj)
  if(obj instanceof RegExp) return new RegExp(obj) 

  if(cache.get(obj)) return cache.get(obj)
  
  // 拿到实例对应的构造函数,new一个新的实例
  let cloneObj = new obj.constructor() 
  cache.set(obj, cloneObj) 

  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      cloneObj[key] = deepClone(obj[key], cache) // 递归拷贝
    }
  }
  return cloneObj
}
const obj = { name: 'Jack', address: { x: 100, y: 200 } }
obj.a = obj // 循环引用
const newObj = deepClone(obj)
console.log(newObj.address === obj.address)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值