LazyMan面试题

Posted xhappyness

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
}

以上是关于LazyMan面试题的主要内容,如果未能解决你的问题,请参考以下文章

面试题 LazyMan 的Rxjs实现方式

前端面试题之手写promise

Java工程师面试题,二级java刷题软件

Java进阶之光!2021必看-Java高级面试题总结

javascript代码

经验总结:Java高级工程师面试题-字节跳动,成功跳槽阿里!