lazyman

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

const self = this;

self.tasks = [];

let fn = (function (n) {

let name = n

    return function () {

console.log(`Hi This is ${name}`);

self.next();

}

})(name);

self.tasks.push(fn);

setTimeout(function () {

self.next();

},0);

}

Lazyman.prototype = {

next() { 

const self = this;

let fn = self.tasks.shift();

fn && fn();

},

sleep(time) {

const self = this;

let fn = (function (time) {

return function () {

setTimeout(function () {

console.log(`Wake up after ${time}`)

self.next();

},time * 1000)

}

})(time);

self.tasks.push(fn);

return self;

},

eat(food) {

const self = this;

let fn = (function (food) {

return function () {

console.log(`Eat ${food}~`)

self.next()

}

})(food);

self.tasks.push(fn);

return self;

},

run(num) {

const self = this;

let fn = (function (num) {

return function () {

console.log(`Run ${num}~`);

self.next();

}

})(num);

self.tasks.push(fn);

return self;

},

fistSleep(time) {

const self = this

    let fn = function (time) {

return function () {

setTimeout(function () {

console.log(`sleep ${time}`)

self.next()

}

,time * 1000)

}

}(time)

self.tasks.unshift(fn)

return self

  }

}

function _lazyman(name) {

return new Lazyman(name);

}

_lazyman('lay-man').sleep(2).eat('mian').run(1100).fistSleep(3);

你可能感兴趣的:(lazyman)