skip to content

🎙️分析一道「微信」面试题

题目:实现一个 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

代码实现:

class LazyManCreator {
  constructor(name) {
    this.taskList = []
    const task = () => {
      console.log(`Hi! This is ${name}!`)
      this.next()
    }
    this.taskList.push(task)
    setTimeout(() => {
      this.next()
    }, 0)
  }
  next() {
    const task = this.taskList.shift()
    task && task()
  }
  sleep(timeout) {
    const task = () => {
      setTimeout(() => {
        console.log(`Wake up after ${timeout}`)
        this.next()
      }, timeout * 1000)
    }
    this.taskList.push(task)
    return this
  }
  sleepFirst(timeout) {
    const task = () => {
      setTimeout(() => {
        console.log(`Wake up after ${timeout}`)
        this.next()
      }, timeout * 1000)
    }
    this.taskList.unshift(task)
    return this
  }
  eat(meal) {
    const task = () => {
      console.log(`Eat ${meal}`)
      this.next()
    }
    this.taskList.push(task)
    return this
  }
}

const LazyMan = name => {
  return new LazyManCreator(name)
}

console.log('==============')
LazyMan('Hank').sleepFirst(5).eat('supper')

追加一道类似的题目:实现下面这道题中的machine函数

function machine() {
    
}
machine('ygy').execute() 
// start ygy
machine('ygy').do('eat').execute(); 
// start ygy
// ygy eat
machine('ygy').wait(5).do('eat').execute();
// start ygy
// wait 5s(这里等待了5s)
// ygy eat
machine('ygy').waitFirst(5).do('eat').execute();
// wait 5s
// start ygy
// ygy eat

代码实现:

function machine(name) {
  class Machine {
    constructor(name) {
      this.name = name
      this.taskList = []
      const task = () => {
        console.log(`start ${this.name}`)
        this.next()
      }
      this.taskList.push(task)
    }
    next() {
      const task = this.taskList.shift()
      task && task()
    }
    execute() {
      this.next()
    }
    do(something) {
      const task = () => {
        console.log(`${this.name} ${something}`)
        this.next()
      }
      this.taskList.push(task)
      return this
    }
    wait(timeout) {
      const task = () => {
        console.log(`wait ${timeout}s`)
        setTimeout(() => {
          this.next()
        }, 1000 * timeout)
      }
      this.taskList.push(task)
      return this
    }
    waitFirst(timeout) {
      const task = () => {
        console.log(`wait ${timeout}s`)
        setTimeout(() => {
          this.next()
        }, 1000 * timeout)
      }
      this.taskList.unshift(task)
      return this
    }
  }
  return new Machine(name)
}