面试题:LazyMan

125 阅读1分钟

考点:同异步、原型、原型链、while while:不确定循环次数;阻止主线程;

要求:

/*实现一个LazyMan,可以按照以下方式调用:
1) LazyMan(“Hank”)输出:
Hi! This is Hank!

2) LazyMan(“Hank”).sleep(10).eat(“dinner”)输出
Hi! This is Hank!
//等待10秒..
Wake up after 10
Eat dinner~

3) LazyMan(“Hank”).eat(“dinner”).eat(“supper”)输出
Hi This is Hank!
Eat dinner~
Eat supper~

4) LazyMan(“Hank”).sleepFirst(5).eat(“supper”)输出
//等待5秒
Wake up after 5
Hi This is Hank!
Eat supper */

解答1:

function LazyMan(name) {
    function Man() {
        setTimeout(function () {
            console.log(`Hi! This is ${name}`);
        },0)
    }
    let t=null;
    Man.prototype.sleep=function (time) {
        t=time;
        setTimeout(function () {
            console.log(`Wake up after ${time}`)
        },time*1000);
        return this;
    }
    Man.prototype.eat=function (food) {
        setTimeout(function () {
            console.log(` Eat ${food}~`)
        },t*1000)
        return this;
    }
    Man.prototype.sleepFirst=function (tim) {
        let curTime = new Date();
        while(new Date()-curTime<=tim*1000){ }
        console.log(`Wake up after ${tim}`)
        return this;
    }
    return new Man();
}

解答二:

const LazyMan = function(name){
  const array = []
  const fn = () => { console.log("Hi! This is "+name+ '!'); next() }
  const next = ()=>{
    const fn = array.shift()
    fn && fn()
  }
  array.push(fn)
  setTimeout(()=>{next()},0)
  const api = {
    sleep: (number) => {
      array.push(()=> {
        setTimeout(()=>{console.log('Wake up after '+ number); next() }, number*1000)
      })
      return api
    },
    eat: (content) => {
      array.push(() => {
        console.log('eat ' + content); next() 
      })
      return api 
    },
    sleepFirst: (number) => { 
      array.unshift(() => {
        setTimeout(()=>{console.log('Wake up after '+5); next() }, number*1000)
      })
      return api
    }
  }
  return api
}