題目要求如下:
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
看到sleep,後面接着其他操作是不是第一反應使用promise,沒錯剛開始我也是這麼想的;但是題目涉及的都是鏈式調用(像jquery那樣,$(‘app’).addClass(‘main’).remove() 。。。),應該要返回當前實例,所以使用promise不符合題目要求。
題目分析:
- 題目需要滿足鏈式調用
- sleepFirst執行優先級最高
- 執行是串行的,執行完A,才能執行完B
一種寫法
class LazyMan{
constructor(name){
console.log(`Hi I am ${name}`)
this.taskList = []
setTimeout(this.next.bind(this), 0)
}
next(){
const fn = this.taskList.shift()
fn && fn()
}
sleep(time){
const fn = ()=>{
setTimeout(()=>{
console.log(`等待了${time}秒`)
this.next()
}, time * 1000)
}
this.taskList.push(fn)
return this
}
sleepFirst(time){
const fn = ()=>{
setTimeout(()=>{
console.log(`等待了${time}秒`)
this.next()
}, time * 1000)
}
this.taskList.unshift(fn)
return this
}
eat(some){
const fn = ()=>{
console.log(`I am eating ${some}`)
this.next()
}
this.taskList.push(fn)
return this
}
}
寫法分析
- 使用數組來實現堆棧
- 每次執行完函數,再顯示的調用下一個函數,這保證了只有執行完A,才能執行完B;
Q&A
1.使用輪詢的方式來執行數組堆棧是否可行?
可行,但是要保證上一個函數執行完畢。
思路:使用一個全局變量來代表當前函數是否執行完畢