LazyMan

1,120 阅读1分钟

题目

实现一个LazyMan,可以按照以下方式调用:

LazyMan('Hank')
// 输出:
// Hi! This is Hank!
LazyMan('Hank').sleep(10).eat('dinner')
// 输出:
// Hi! This is Hank!
// 等待10秒
// Wake up after 10
// Eat dinner~
LazyMan('Hank').eat('dinner').eat('supper')
// 输出:
// Hi This is Hank!
// Eat dinner~
// Eat supper~
LazyMan('Hank').sleepFirst(5).eat('supper')
// 输出:
// 等待5秒
// Wake up after 5
// Hi This is Hank!
// Eat supper
// 以此类推。

题解

function LazyMan (name) {
  function Man (name) {
    this.todo = []
    this.todo.push(() => {
      console.log(`Hi! This is ${name}!`)
      this._next()
    })
    setTimeout(() => {
      this._next()
    }, 0);
    return this
  }
  Man.prototype._next = function () {
    const fn = this.todo.shift()
    fn && fn()
  }
  Man.prototype.sleep = function (second) {
    this.todo.push(() => {
      setTimeout(() => {
        console.log(`Wake up after ${second}`)
        this._next()
      }, second * 1000)
    })
    return this
  }
  Man.prototype.sleepFirst = function (second) {
    this.todo.unshift(() => {
      setTimeout(() => {
        console.log(`Wake up after ${second}`)
        this._next()
      }, second * 1000)
    })
    return this
  }
  Man.prototype.eat = function (which) {
    this.todo.push(() => {
      console.log(`Eat ${which}~`)
      this._next()
    })
    return this
  }
  return new Man(name)
}

参考

zhuanlan.zhihu.com/p/22387417