• 面试题-lazyMan实现


    原文:如何实现一个LazyMan

    面试题目

    实现一个LazyMan,可以按照以下方式调用:

    LazyMan('Hank'),输出:

    Hi, This is Hank!

    LazyMan('Hank').sleep(5).eat('dinner'),输出:

    Hi, This is Hank!
    // 等待5秒
    Weak 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

    以此类推

    题目解析

    • 需要封装一个对象,并且这个对象提供不同的方法,比如eat
    • 能进行链式调用,那么每个调用方法,都必须返回当前对象
    • sleepsleepFirst方法需要时异步的

    解题思路

    • 采用 ES6 的 class,来实现,封装对象_LazyMan
    • 提供一系列方法,比如eatsleepsleepFirst异步方法采用PromisesetTimeout实现
    • 链式调用,考虑到其中含异步方法,采用任务队列及 ES6 的async wait实现。每次调用都往队列中加入方法,然后循环调用任务队列,而循环中通过异步实现异步的方法,保证正确。

    具体实现

    class _LazyMan {
      constructor (name) {
        this.taskQueue = [];
        this.runTimer = null;
        this.sayHi(name);
      }
    
      run () {
        if (this.runTimer) {
          clearTimeout(this.runTimer);
        }
    
        this.runTimer = setTimeout(async () => {
          for (let asyncFun of this.taskQueue) {
            await asyncFun()
          }
          this.taskQueue.length = 0;
          this.runTimer = null;
        })
        return this;
      }
    
      sayHi (name) {
        this.taskQueue.push(async () => console.log(`Hi, this is ${name}`));
        return this.run();
      }
    
      eat (food) {
        this.taskQueue.push(async () => console.log(`Eat ${food}`));
        return this.run();
      }
    
      sleep (second) {
        this.taskQueue.push(async () => {
          console.log(`Sleep ${second} s`)
          return this._timeout(second)
        });
        return this.run();
      }
    
      sleepFirst (second) {
        this.taskQueue.unshift(async () => {
          console.log(`Sleep first ${second} s`)
          return this._timeout(second);
        });
        return this.run();
      }
    
      async _timeout (second) {
        await new Promise(resolve => {
          setTimeout(resolve, second * 1e3);
        })
      }
    }
    
    // 测试
    var LazyMan = name => new _LazyMan(name)
    
    // lazyMan('Hank');
    lazyMan('Hank').sleep(10).eat('dinner');
    // lazyMan('Hank').eat('dinner').eat('supper');
    // lazyMan('Hank').sleepFirst(5).eat('supper');
    
  • 相关阅读:
    Quartz:基本用法总结
    Linux: ssh免密登陆
    AOP计算方法执行时长
    架构师常用的5种图
    正态分布及正态随机变量
    【转】Ubuntu下解决Depends: xxx(< 1.2.1) but xxx is to be installed
    Robotium和Espresso大PK——速度篇
    使用docker安装mysql并连接
    直接拷贝数据文件实现Oracle数据迁移
    ORA-08103:对象不再存在
  • 原文地址:https://www.cnblogs.com/EnSnail/p/9866130.html
Copyright © 2020-2023  润新知