frontEnd_book icon indicating copy to clipboard operation
frontEnd_book copied to clipboard

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

Open hanyueqiang opened this issue 4 years ago • 0 comments

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

实现如下:

class Lazy {
  constructor(name) {
    this.name = name;
    this.queue = [];
    console.log(`Hi I am ${name}`);
    setTimeout(() => {
      this.next()
    },0)
  }
  sleep(delay) {
    const self = this;
    const s = function() {
        setTimeout(()=> {
          console.log(`等待了${delay}秒...`);
          self.next();
        },delay*1000);
    };
    this.queue.push(s);
    return this;
  }
  eat(food) {
    const self = this;
    const e = function() {
        console.log(`I am eating ${food}`);
        self.next();
    }
    this.queue.push(e);
    return this;
  }
  next() {
    const fn = this.queue.shift();
    fn && fn();
  }
  sleepFirst(delay) {
    const self = this;
    const first = function() {
      setTimeout(() => {
        console.log(`等待了${delay}秒...`);
        self.next();
      },delay*1000)
    }
    this.queue.unshift(first);
    return this;

  }
}

function LazyMan(name) {
  return new Lazy(name);
}

hanyueqiang avatar Nov 22 '20 16:11 hanyueqiang