xiaoyu2er / blog

小鱼二的博客, 喜欢的话请点star :D
337 stars 37 forks source link

实现一个 LazyMan #12

Open xiaoyu2er opened 6 years ago

xiaoyu2er commented 6 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

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

class _LazyMan {
    constructor(name) {
        this.tasks = [];
        this.canExecute = true;

        var task = function lazyMan(cb) {
            console.log(`Hi This is ${name}`);
            cb();
        };

        this.addTask(task);
    }

    eat(food) {
        var task = function eat(cb) {
            console.log(`Eat ${food}~`);
            cb();
        }
        this.addTask(task);
        return this;
    }

    sleep(sec) {
        var task = function sleep(cb) {
            setTimeout(() => {
                console.log(`Wake up after ${sec}`);
                cb();
            }, sec * 1000);
        };
        this.addTask(task);
        return this;
    }

    sleepFirst(sec) {
        var task = function sleepFirst(cb) {
            setTimeout(() => {
                console.log(`Wake up after ${sec}`);
                cb();
            }, sec * 1000);
        };
        this.addTask(task, true);
        return this;
    }

    addTask(task, first) {
        if (first) {
            this.tasks.unshift(task);
        } else {
            this.tasks.push(task);
        }
        this.executeTasks();
    }

    executeTasks() {
        setTimeout(() => {
            if (!this.canExecute) return;
            this.canExecute = false;
            var task = this.tasks.shift();

            if (task) {
                // console.log(task.name);
                task(() => {
                    this.canExecute = true;
                    this.executeTasks();
                });
            }
        }, 0);

    }
}

// LazyMan('Hank');
// LazyMan('Hank').eat('dinner').eat('supper')
// LazyMan('Hank').sleep(2).eat('dinner');
// LazyMan('Hank').eat('dinner').eat('supper');
LazyMan('Hank').sleepFirst(2).eat('supper');