JSFiddle - React, Tailwind, and code Playground

by leopoldthecuber

JavaScript

// // // // 先来道热身题:生成一个随机整数,范围是 300 - 1000
// function random() {
//   return parseInt(`${Math.random()*10*1000}`, 10)%700+300;
// }
// // console.log(random());
// // console.log(random());
// // console.log(random());
// // console.log(random());

// // 接下来用刚才的随机数方法,模拟一次 api 请求的过程:
// // 由于网络延迟,本地和服务器之间会有随机的延迟,范围是 300 - 1000 ms。
// // api 请求会返回请求到达服务器时服务器的时间戳。
// // 提示:由于随机延时,返回的时间戳每次运行应该不同。同时发起的请求,返回的时间戳可能不是顺序的。


// function api(): Promise<number> {
//   const time = random();
//   return new Promise((resolve) => {
//     setTimeout(()=>{
//       const respTime = random();
//       const timestamp = Date.now();
//       setTimeout(()=>{
//         resolve(timestamp);
//       }, respTime);
//     }, time);
//   });
// }

// api().then(console.log)

// 实现一个eventEmitter
function Emitter(){
  this.map = {};
  this.all = [];
}

Emitter.prototype.on = function(event, callback) {

  // TODO 
  if(event === '*'){
    this.all.push(callback);
  }
  
  let list = this.map[event];
  if(!list) {
    list = [];
    this.map[event] = list;
  }
  list.push(callback);
}

Emitter.prototype.off = function(event, callback)  {
  if(event === '*'){
    this.all = this.all.filter((item)=>item === callback);
  }
  
  let list = this.map[event];
  if(!list) { return; }
  list = list.filter((item)=>item === callback);
  this.map[event] = list;
}

Emitter.prototype.emit = function(event, e) {
  this.all.forEach(fn=>{
    fn(event, e);
  })
  
  const list = this.map[event];
  if(!list) return;
  list.forEach(fn=>{
    fn(e);
  })
}

Emitter.prototype.clear = function() {
  this.map = {};
}

//使下面的代码可以成功执行
const emitter = new Emitter()
// listen to an event
// TODO 
emitter.on('foo', e => console.log('foo', e) )
// listen to all events
emitter.on('*', (type, e) => console.log(type, e) )
// fire an event
emitter.emit('foo', { a: 'b' })
// clearing all events
emitter.clear()
// working with handler references:
function onFoo() {}
emitter.on('foo', onFoo)   // listen
emitter.off('foo',...