lllyin / learning

前端踩坑记
2 stars 0 forks source link

Lazyman面试题尝解 #1

Open lllyin opened 4 years ago

lllyin commented 4 years ago

题目:

实现一个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 LazyManMain {
  constructor(name) {
    this.name = name;
    this.tasks = [];
    this.say();
    setTimeout(() => this.run(), 0);
  }

  run() {
    const tasksPromise = this.tasks.map(task => async () => this.toPromise(task.fn, task.duration));
    this.mergePromise(tasksPromise);
  }

  mergePromise(promiseTask) {
    let p = Promise.resolve();
    promiseTask.forEach(promise => {
      p = p.then(promise).then(d => {});
    });
  }

  toPromise(fn, duration) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        try {
          resolve(fn());
        } catch (err) {
          reject(err);
        }
      }, duration);
    });
  }

  say() {
    const say = () => {
      console.log(`Hi! this is ${this.name}!`);
    };
    this.tasks.push({ fn: say });
    return this;
  }

  sleepFirst(duration) {
    const sleepFirst = function() {
      console.log(`Wake up after ${duration}`);
    };
    this.tasks.unshift({ fn: sleepFirst, duration });
    return this;
  }

  sleep(duration) {
    const sleep = function() {
      console.log(`Wake up after ${duration}`);
    };
    this.tasks.push({ fn: sleep, duration });
    return this;
  }

  eat(food) {
    const eat = function() {
      console.log(`Eat ${food}`);
    };
    this.tasks.push({ fn: eat });
    return this;
  }
}

function LazyMan(name) {
  return new LazyManMain(name);
}

LazyMan('Hank')
  .sleepFirst(1500)
  .eat('dinner');
lllyin commented 4 years ago

抛砖引玉,代码量还是挺多的,应该会有更简洁的写法。

lllyin commented 4 years ago

找到一篇解题的帖子 LazyMan 有几样写法,你知道么?