码疯窝

微信的一道面试题LazyMan的简单实现。

2017/01/23 18:51:26    分类: 技术随笔    0人评论 次浏览

题目如下:

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

  1. LazyMan('Hank')
  2. Hi! This is Hank!
  3. LazyMan('Hank').sleep(10).eat('dinner')
  4. Hi! This is Hank!
  5. //等待10秒..
  6. Wake up after 10
  7. Eat dinner~
  8. LazyMan('Hank').eat('dinner').eat('supper')
  9. Hi This is Hank!
  10. Eat dinner~
  11. Eat supper~
  12. LazyMan('Hank').sleepFirst(5).eat('supper')
  13. //等待5秒
  14. Wake up after 5
  15. Hi This is Hank!
  16. Eat supper

以此类推。

主要考察两个点:

  • 链式调用
  • 队列

实现代码如下:

  1. class C {
  2. constructor (name) {
  3. this.tasks = [];
  4. setTimeout(() => this.next());
  5. return this.push(() => new Promise(r => console.log(`Hi! This is ${name}`) || r()));
  6. }
  7. next () {
  8. let task = this.tasks.shift();
  9. task && task().then(() => this.next());
  10. }
  11. push (v) {
  12. this.tasks.push(v);
  13. return this;
  14. }
  15. unshift (v) {
  16. this.tasks.unshift(v);
  17. return this;
  18. }
  19. sleep (sec) {
  20. return this.push(() => new Promise(r => console.log(`//等待${sec}秒..`) || setTimeout(() => console.log(`Wake up after ${sec}`) || r(), 1000 * sec)));
  21. }
  22. sleepFirst (sec) {
  23. return this.unshift(() => new Promise(r => console.log(`//等待${sec}秒..`) || setTimeout(() => console.log(`Wake up after ${sec}`) || r(), 1000 * sec)));
  24. }
  25. eat (name) {
  26. return this.push(() => new Promise(r => console.log(`Eat ${name}`) || r()));
  27. }
  28. }
  29. const LazyMan = function (name) {
  30. return new C(name);
  31. }
  32. LazyMan('Gcaufy').eat('dinner').sleep(3).eat('supper').sleepFirst(2);
继续查看有关 技术随笔的文章

0个访客评论