Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现一个 LazyMan #12

Open
xiaoyu2er opened this issue Apr 11, 2018 · 0 comments
Open

实现一个 LazyMan #12

xiaoyu2er opened this issue Apr 11, 2018 · 0 comments

Comments

@xiaoyu2er
Copy link
Owner

实现一个 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');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant