美文网首页
LazyMan 实现...

LazyMan 实现...

作者: 行走的蛋白质 | 来源:发表于2021-04-23 09:33 被阅读0次

    // 实现一个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 Cp {
      constructor(name) {
        this.tasks = [];
        const task = (name => _ => {
          console.log(`Hi! This is ${name}!`);
          this.next();
        })(name);
        this.tasks.push(task);
        setTimeout(_ => {
          this.next();
        })
      }
    
      next() {
        const task = this.tasks.shift();
        task && task();
      }
    
      eat(food) {
        const task = (food => _ => {
          console.log(`Eat ${food}~`);
          this.next();
        })(food);
        this.tasks.push(task);
        return this;
      }
    
      sleep(wait) {
        const task = (wait => _ => {
          setTimeout(_ => {
            console.log(`Wake up after ${wait}`);
            this.next();
          }, wait * 1000);
        })(wait);
        this.tasks.push(task);
        return this;
      }
    
      sleepFirst(wait) {
        const task = (wait => _ => {
          setTimeout(_ => {
            console.log(`Wake up after ${wait}`);
            this.next();
          }, wait * 1000);
        })(wait);
        this.tasks.unshift(task);
        return this;
      }
    }
    
    function LazyMan(name) {
      return new Cp(name);
    }
    
    LazyMan('hank').sleep(3).eat('dog').eat('chicken').sleepFirst(5);
    

    相关文章

      网友评论

          本文标题:LazyMan 实现...

          本文链接:https://www.haomeiwen.com/subject/titcrltx.html