每日一题之手写lazyman, 支持链式调用

80 阅读1分钟

手写lazyman, 支持链式调用

  • 思路:
    • 在函数被构造的时候调用一次next函数, tasks数组中存储的是各种各样的函数, 执行next函数就会从数组头部取出一个去执行, 准确先进先出的原则, 之所以可以使用链式调用, 是因为每个函数(sleep, eat)都返回了this, 也就是当前的构造函数
class LazyMan {
  constructor(name) {
    this.name = name;
    this.tasks = [];
    console.log(`I am ${this.name}`);

    setTimeout(() => {
      this.next();
    }, 0);
  }

  next() {
    const task = this.tasks.shift();
    task && task();
  }

  sleep(time) {
    const task = () => {
      setTimeout(() => {
        console.log(`waiting for ${time}s`);
        this.next();
      }, time * 1000);
    };
    this.tasks.push(task);
    return this;
  }

  eat(food) {
    const task = () => {
      setTimeout(() => {
        console.log(`I want to eat ${food}`);
        this.next();
      }, 0);
    };
    this.tasks.push(task);
    return this;
  }
}

function lazyMan(name) {
  return new LazyMan(name);
}

lazyMan("dzl")
  .eat("苹果")
  .sleep(1)
  .eat("哈希")
  .sleep(2)
  .eat("香蕉")
  .sleep(3)
  .eat("睡觉");