Lazyman功能实现

Posted 洛河

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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~

实现代码:

var task = [];
function next(){
if(task && task.length > 0) {
task.shift()();
}
}
function lazyMan(a) {
setTimeout(next, 0);
}

function LazyMan(a) {
task = [];
return new lazyMan().init(a);
}
lazyMan.prototype = {
init: function(a) {
var fn = function() {
console.log("Hi! This is " + a + "!");
next();
}
task.push(fn);
return this;
},
sleep: function(t) {
var fn = function() {
setTimeout(function() {
console.log("Wake up after " + t);
next();
}, t * 1000);
}
task.push(fn);
return this;
},
eat: function(d) {
var fn = function() {
console.log("Eat " + d + "~");
next();
}
task.push(fn);
return this;
},
sleepFirst: function(t) {
var fn = function() {
setTimeout(function() {
console.log("Wake up after " + t);
next();
}, t * 1000);
}
task.unshift(fn);
return this;
}

}

代码实现的思考:

1.javascript流程控制实现需要利用中间件原理;

2.JavaScript利用return this实现链式调用;

以上是关于Lazyman功能实现的主要内容,如果未能解决你的问题,请参考以下文章

面试题-lazyMan实现

LazyMan的实现

面试题 LazyMan 的Rxjs实现方式

实现一个简单的lazyman

es5和es6实现lazyman

LazyMan面试题