// 实现一个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
class Cp {
constructor(name) {
this.tasks = [];
const task = (name => _ => {
console.log(`Hi! This is ${name}!`);
this.next();
})(name);
this.tasks.push(task);
setTimeout(_ => {
this.next();
})
}
next() {
const task = this.tasks.shift();
task && task();
}
eat(food) {
const task = (food => _ => {
console.log(`Eat ${food}~`);
this.next();
})(food);
this.tasks.push(task);
return this;
}
sleep(wait) {
const task = (wait => _ => {
setTimeout(_ => {
console.log(`Wake up after ${wait}`);
this.next();
}, wait * 1000);
})(wait);
this.tasks.push(task);
return this;
}
sleepFirst(wait) {
const task = (wait => _ => {
setTimeout(_ => {
console.log(`Wake up after ${wait}`);
this.next();
}, wait * 1000);
})(wait);
this.tasks.unshift(task);
return this;
}
}
function LazyMan(name) {
return new Cp(name);
}
LazyMan('hank').sleep(3).eat('dog').eat('chicken').sleepFirst(5);
网友评论