题目
实现一个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.fn.init(name);}lazyman.fn = lazyman.prototype = { construct: lazyman, stack: null, status: 0, init: function (name) { this.name = name; this.stack = []; return this; }, sleep: function (time) { var that = this; time = +time; if(time !== time) { this.next(); } else if(this.status) { this.stack.unshift(this.sleep.bind(this, time)); } else { this.status = 1; this.print(`sleeping ${time} seconds...`); setTimeout(function () { that.status = 0; that.next(); }, time * 1000); } return this; }, next: function () { while(this.status == 0 && this.stack.length) { this.print( this.stack.pop()() ); } return this; }, eat: function(thing) { this.stack.unshift(lazyEat.bind(null, this.name, thing)); if(this.status == 0) { this.next(); } return this; }, print: console.log}lazyman.fn.init.prototype = lazyman.fn;function lazyEat(name, thing) { return `${name} eat ${thing}`;}module.exports = lazyman;