snail3157 / myBlog

0 stars 0 forks source link

要求设计 LazyMan 类,实现以下功能 #2

Open snail3157 opened 5 years ago

snail3157 commented 5 years ago
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
snail3157 commented 5 years ago
class LazyManClass {
  constructor(name) {
    this.todoList = []
    this.activeLastFirstSleepindex = 0
    console.log(`Hi I am ${name}`)
    setTimeout(() => {
      this.doList()
    }, 0);
    return this
  }
  _sleep(time) {
    return () => {
      console.log(`等待了${time}秒...`)
    }
  }
  sleep(time) {
    this.todoList.push(
      {
        fn: this._sleep(time),
        time: time,
        isSleep: true
      }
    )
    this.activeLastFirstSleepindex = this.todoList.length
    return this
  }
  sleepFirst(time) {
    let handler = 
      {
        fn: this._sleep(time),
        time: time,
        isSleep: true
      }
    let start = this.todoList.slice(0, this.activeLastFirstSleepindex)
    let end = this.todoList.slice(this.activeLastFirstSleepindex)
    this.todoList = [...start, handler, ...end]
    this.activeLastFirstSleepindex++
    return this
  }
  _eat(food) {
    return () => {
      console.log(`I am eating ${food}`)
    }
  }
  eat(food) {
    this.todoList.push(
      {
        fn: this._eat(food),
        isSleep: false
      }
    )
    return this
  }
  async doList() {
    let arr = this.todoList
    for(let i=0,len=arr.length;i<len;i++) {
      if (!arr[i].isSleep) {
        await arr[i].fn()
      } else {
        await new Promise((resolve, reject) => {
          setTimeout(() => {
            arr[i].fn()
            resolve()
          }, arr[i].time*1000);
        })
      }
    }
  }
}
function LazyMan(name) {
  return new LazyManClass(name)
}
LazyMan('Tony').sleep(3).eat('lunch').sleepFirst(2).eat('dinner').sleepFirst(5).sleep(10).eat('junk food').sleepFirst(7);