LazyMan 效果实现

36 阅读1分钟

💡 Tips:经典面试题 LazyMan 效果实现

需求

// LazyMan('Tony');
// Hi I am Tony

// LazyMan('Tony').sleep(10).eat('lunch');
// Hi I am Tony
// 等待了10秒...
// I am eating lunch

// LazyMan('Tony').eat('lunch').sleep(10).eat('dinner');
// Hi I am Tony
// I am eating lunch
// 等待了10秒...
// I am eating diner

// LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food');
// Hi I am Tony
// 等待了5秒...
// I am eating lunch
// I am eating dinner
// 等待了10秒...
// I am eating junk food

代码实现

class LazyMan {
  taskList = [];
  isExecuting = false;
  constructor(name) {
      this.log(`Hi I am ${name}`);
  }
  sleepFirst(waitSecond) {
      this.sleep(waitSecond, false);
  }
  sleep(waitSecond, isPush = true) {
      this.addTask((cb) => {
          setTimeout(() => {
              this.log(`等待了${waitSecond}秒。。。`)
              cb();
          }, waitSecond * 1000);
      }, isPush);
      return this;
  }
  eat(food) {
      this.addTask((cb) => {
          this.log(`I am eating ${food}`);
          cb();
      });
      return this;
  }
  next() {
      const { taskList, isExecuting } = this;
      if (isExecuting || !taskList.length) return;
      this.isExecuting = true;

      setTimeout(() => {
          const task = this.taskList.shift();
          if (!!task && (typeof task).toLowerCase() === 'function') {
              task(this.cb.bind(this));
          }
      }, 0);
  }
  addTask(task, isPush = true) {
      if (isPush) {
          this.taskList.push(task);
      } else {
          this.taskList.unshift(task);
      }
      this.next();
  }
  cb() {
      this.isExecuting = false;
      this.next();
  }
  log(val) {
      console.log(val);
  }
}

const lazyMan = new LazyMan('Tony');
lazyMan.eat('lunch').sleep(10).eat('dinner').sleepFirst(3);

💡 Tips:xdm,转载请附上链接;如有错误,请不吝指出,必将及时订正!!! www.yuque.com/jslover/ldr…