# 一道题看事件队列怎么写

# 要求设计 LazyMan 类,实现以下功能。

LazyMan('Tony');
// Hi I am Tony

LazyMan('Tony').sleep(10).eat('lunch');
// Hi I am Tony
// 等待了10秒...
// I am eating lunch

LazyMan('Tony').eat('lunch').sleep(10).eat('dinner');
// Hi I am Tony
// I am eating lunch
// 等待了10秒...
// I am eating diner

LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food');
// Hi I am Tony
// 等待了5秒...
// I am eating lunch
// I am eating dinner
// 等待了10秒...
// I am eating junk food

从题意可以看出我们需要实现的功能有

  • 事件队列: sleepFirst需要把休眠提到最前面,所以需要自己模拟实现事件队列,自定义事件执行顺序
  • 链式调用:通过方法内返回 this 实现
class _LazyMan {
    constructor(name) {
        this.name = name;
        this.tasks = [];
        console.log('Hi I am ', name);
        setTimeout(() => {
            this.next();
        }, 0)
    }
    sleep(time) {
        const fn = () => {
            setTimeout(() => {
                console.log(`等待了${time}秒...`)
                this.next();
            }, time)
        }
        this.tasks.push(fn);
        return this;
    }
    // 影响队列操作 sleep放到队列前面
    sleepFirst(time) {
        const fn = () => {
            setTimeout(() => {
                console.log(`等待了${time}秒...`);
                this.next()
            }, time)
        }
        this.tasks.unshift(fn);
        return this;
    }
    eat(food) {
        const fn = () => {
            console.log(`I am eating ${food}`);
            this.next();
        }
        this.tasks.push(fn);
        return this;
    }
    next() {
        const fn = this.tasks.shift();
        fn && fn();
    }
}
function LazyMan(name) {
    return new _LazyMan(name);
}