SOURCE

// LazyMan除了吃就是睡,很lazy。

// LazyMan(name: string, logFn: (log: string) => void) 通过传入logFn打印信息。

// LazyMan('Jack', console.log)
// // Hi, I'm Jack.
// 可以eat(food: string)

// LazyMan('Jack', console.log)
//   .eat('banana')
//   .eat('apple')
// // Hi, I'm Jack.
// // Eat banana.
// // Eat Apple.
// 可以sleep(time: number),单位是秒。

// LazyMan('Jack', console.log)
//   .eat('banana')
//   .sleep(10)
//   .eat('apple')
//   .sleep(1)
// // Hi, I'm Jack.
// // Eat banana.
// // Wake up after 10 seconds.
// // Eat Apple.
// // Wake up after 1 second.
// sleepFirst(time: number)的话,无论顺序如何,最优先sleep。

// LazyMan('Jack', console.log)
//   .eat('banana')
//   .sleepFirst(10)
//   .eat('apple')
//   .sleep(1)
// // Wake up after 10 seconds.
// // Hi, I'm Jack.
// // Eat banana
// // Eat apple
// // Wake up after 1 second.
// 请创建一个如此懒惰的LazyMan()。



class LazyMan {
    constructor(name, callbak) {
        this.name = name;
        this.logFn = callbak;

        this.firstTasks = [];
        this.tasks = [];

        setTimeout(() => {
            const task = async () => {
                await this.next(this.firstTasks);
                this.logFn(`Hi I'm ${this.name}`);
                await this.next(this.tasks);
            }
            task();
        }, 0);
    };

    async next() {
        for (const task of tasks) {
            await task();
        }
    };

    eat(food) {
        this.tasks.push(async () => {
            this.logFn(`I eat ${food}`);
        });
        return this;
    }

    sleep(time) {
        this.tasks.push(async () => {
            await new Promise((resolve) => setTimeout(resolve, time * 1000));
            this.logFn(`Wake up after ${time} seconds.`);
        });

        return this;

    }

    sleepFirst(time) {
        this.firstTasks.unshift(async () => {
            await new Promise((resolve) => setTimeout(resolve, time * 1000));
            this.logFn(`Wake up after ${time} seconds.`);
        });

        return this;
    };
};

const lazy = new LazyMan('Jack', console.log);
lazy.eat('banana')
    .sleepFirst(10)
    .eat('apple')
    .sleep(1)
    .eat('finnally')
console 命令行工具 X clear

                    
>
console