zoukankan      html  css  js  c++  java
  • LazyMan面试题

    题目

    实现一个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 Man {
      constructor(name) {
        this.actions = [];
        const hello = () => {
          console.log(`Hi This is ${name}!`);
          this.next();
        };
    
        this.addAction(hello);
        setTimeout(() => {
          this.next();
        }, 0);
      }
    
      next() {
        if (this.actions.length > 0) {
          const fn = this.actions.shift();
          if ((typeof fn).toLowerCase() === 'function') {
            fn();
          }
        }
      }
    
      addAction(func, isFirst) {
        if (!isFirst) {
          this.actions.push(func);
        } else {
          this.actions.unshift(func);
        }
      }
    
      eat(food) {
        const eatFunc = () => {
          console.log(`Eat ${food}~`);
          this.next();
        };
        this.addAction(eatFunc);
        return this;
      }
    
      sleep(time) {
        const sleepFn = () => {
          setTimeout(() => {
            console.log(`Wake up after ${time}ms`);
            this.next();
          }, time);
        };
        this.addAction(sleepFn);
        return this;
      }
    
      sleepFirst(time) {
        const sleepFirst = () => {
          setTimeout(() => {
            console.log(`Wake up after ${time}ms`);
            this.next();
          }, time);
        };
    
        this.addAction(sleepFirst, true);
        return this;
      }
    }
    
    function LazyMan(name) {
      return new Man(name);
    }
    
  • 相关阅读:
    NFS与通配符
    yum管理RPM包与linux网络设置
    git常用命令总结——覆盖日常开发全操作
    inner join on会过滤掉两边空值的条件
    入园第一天
    P3750 [六省联考2017]分手是祝愿 题解
    CSP2021 爆零记
    CSP 前模板记录(黄题篇)
    对拍
    2021.10.20CSP模拟模拟赛 赛后总结
  • 原文地址:https://www.cnblogs.com/XHappyness/p/12212790.html
Copyright © 2011-2022 走看看