设计一个 LazyMan 类
要求设计 LazyMan 类,实现以下功能
LazyMan('Tony');
// Hi I am Tony
LazyMan('Tony').sleep(10).eat('lunch');
// Hi I am Tony
// 等待了10秒...
// I am eating lunch
LazyMan('Tony').eat('lunch').sleep(10).eat('dinner');
// Hi I am Tony
// I am eating lunch
// 等待了10秒...
// I am eating diner
LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food');
// Hi I am Tony
// 等待了5秒...
// I am eating lunch
// I am eating dinner
// 等待了10秒...
// I am eating junk food代码
class LazyMans {
constructor(name) {
this.name = name;
this.queen = [];
setTimeout(() => {
this._next();
}, 0);
}
sleep(wait, isFiset = false) {
const _sleep = () => {
setTimeout(() => {
console.log(`等待了${wait}秒`);
this._next();
}, wait * 1000);
};
isFiset ? this.queen.unshift(_sleep) : this.queen.push(_sleep);
return this;
}
_next() {
if (!this.queen.length) return;
let shift = this.queen.shift();
shift.call(this);
}
eat(food) {
const _eat = () => {
console.log(`I am eating ${food}`);
this._next();
};
this.queen.push(_eat);
return this;
}
sleepFirst(wait) {
return this.sleep(wait, true);
}
}
function LazyMan(name) {
return new LazyMans(name);
}