Open dorseysen opened 5 years ago
// 这里的核心其实就是实现一个简单的任务消费队列
class _LazyMan {
constructor (personName) {
this.personName = personName;
this.task = [];
this.init();
}
init () {
let _self = this;
let fn = function () {
console.log('Hi! This is ' + _self.personName + '!');
_self.next();
}
_self.task.push(fn);
setTimeout(() => _self.next(), 0);
}
// 队列指针往右位移一位并删除队列指针前面的已完成任务。
next () {
let fn = this.task.shift();
fn && fn();
}
eat (meal) {
let _self = this;
let fn = function () {
console.log('Eat ' + meal + '~');
_self.next();
}
this.task.push(fn);
return this;
}
sleep (time) {
let _self = this;
let fn = function () {
// console.log('sleep ing...');
setTimeout(() => {
console.log('sleep completed, Wake up after ' + time + ' second');
_self.next();
}, time * 1000);
}
this.task.push(fn);
return this;
}
sleepFirst (time) {
let _self = this;
let fn = function () {
// console.log('sleepFirst ing...');
setTimeout(() => {
console.log('sleepFirst completed, Wake up after ' + time + ' second');
_self.next();
}, time * 1000);
}
this.task.unshift(fn);
return this;
}
}
function LazyMan (personName) {
return new _LazyMan(personName);
}
// LazyMan('Hank').sleep(10);
// LazyMan("Hank").sleep(5).eat("dinner");
LazyMan("dorsey").eat("breakfirst").sleep(2).eat("lunch").sleep(2).eat("dinner").sleepFirst(2);