Open snail3157 opened 5 years ago
class LazyManClass {
constructor(name) {
this.todoList = []
this.activeLastFirstSleepindex = 0
console.log(`Hi I am ${name}`)
setTimeout(() => {
this.doList()
}, 0);
return this
}
_sleep(time) {
return () => {
console.log(`等待了${time}秒...`)
}
}
sleep(time) {
this.todoList.push(
{
fn: this._sleep(time),
time: time,
isSleep: true
}
)
this.activeLastFirstSleepindex = this.todoList.length
return this
}
sleepFirst(time) {
let handler =
{
fn: this._sleep(time),
time: time,
isSleep: true
}
let start = this.todoList.slice(0, this.activeLastFirstSleepindex)
let end = this.todoList.slice(this.activeLastFirstSleepindex)
this.todoList = [...start, handler, ...end]
this.activeLastFirstSleepindex++
return this
}
_eat(food) {
return () => {
console.log(`I am eating ${food}`)
}
}
eat(food) {
this.todoList.push(
{
fn: this._eat(food),
isSleep: false
}
)
return this
}
async doList() {
let arr = this.todoList
for(let i=0,len=arr.length;i<len;i++) {
if (!arr[i].isSleep) {
await arr[i].fn()
} else {
await new Promise((resolve, reject) => {
setTimeout(() => {
arr[i].fn()
resolve()
}, arr[i].time*1000);
})
}
}
}
}
function LazyMan(name) {
return new LazyManClass(name)
}
LazyMan('Tony').sleep(3).eat('lunch').sleepFirst(2).eat('dinner').sleepFirst(5).sleep(10).eat('junk food').sleepFirst(7);