LazyMan

LazyMan

需求

实现 LazyMan,能按以下方式调用:
> LazyMan("Hank")
你好,我是 Hank
> LazyMan("Hank").sleep(10)
  .eat("lunch")
你好,我是 Hank
(沉默十秒)
我醒了,我刚睡了 10 秒
吃午餐
> LazyMan("Hank").eat("lunch")
  .eat("supper")
你好,我是 Hank
吃午餐
吃晚餐
> LazyMan("Hank").sleepFirst(5)
  .eat("supper")
(沉默五秒)
我醒了,我刚睡了 5 秒
你好,我是 Hank
吃晚餐
LazyMan = (name)=>{   // LazyMan('Frank').sleepFirst(5).eat('supper')
  var queue = []
  const task = () => {console.log(`你好,我是${name}`); next()}
  queue.push(task)
  const next = ()=>{ const first = queue.shift(); first?.() }
  var api = {
    _x: queue,
    sleep(n){
      const task = ()=> {
        setTimeout(()=>{console.log(`我醒了,我刚睡了${n}秒`); next()},n*1000)
      }
      queue.push(task)
      return api

    },
 eat(type){
      const task = ()=> {console.log(type === 'lunch' ? '吃午餐':'吃晚餐'); next()}
      queue.push(task)
      return api
    },
    sleepFirst(n){
      const task = ()=> {
        setTimeout(()=>{console.log(`我醒了,我刚睡了${n}秒`); next()},n*1000)
      }
      queue.unshift(task)
      return api
    }
  }
  setTimeout(()=>{ next() })
  return api
}

你可能感兴趣的:(LazyMan)