ZhengXingchi / ZhengXingchi.github.io

Apache License 2.0
0 stars 0 forks source link

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

Open ZhengXingchi opened 4 years ago

ZhengXingchi commented 4 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
ZhengXingchi commented 4 years ago

主要考察了链式操作 数组操作 this的使用

 class LazyManClass {
      constructor(name) {
        console.log(name)
        this.tasks = []

        setTimeout(() => {
          this.next()
        }, 0)
      }
      sleep(time) {
        this.tasks.push(() => {
          setTimeout(() => {
            console.log(time)

            this.next()
          }, time * 1000)
        })
        return this
      }
      sleepFirst(time) {
        this.tasks.unshift(() => {
          setTimeout(() => {
            console.log(time)

            this.next()
          }, time * 1000)
        })
        return this
      }
      eat(lunch) {
        this.tasks.push(() => {
          console.log(lunch)
          this.next()
        })
        return this
      }

      next() {
        let fn = this.tasks.shift()
        fn && fn()

      }
    }
    function LazyMan(name) {
      return new LazyManClass(name)
    }

    LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food')