Skip to content

实现一个 LazyMan #12

@xiaoyu2er

Description

@xiaoyu2er

实现一个 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');

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy