原文:如何實作一個LazyMan
面試題目
實作一個LazyMan,可以按照以下方式調用:
LazyMan('Hank')
,輸出:
Hi, This is Hank!
LazyMan('Hank').sleep(5).eat('dinner')
// 等待5秒
Weak up after 10
Eat dinner ~
LazyMan('Hank').eat('dinner').eat('supper')
,輸出
Hi, this is Hank!
Eat supper ~
LazyMan('Hank').sleepFirst(5).eat('supper')
Wake up after 5
Eat supper
以此類推
題目解析
- 需要封裝一個對象,并且這個對象提供不同的方法,比如
eat
- 能進行鍊式調用,那麼每個調用方法,都必須傳回目前對象
-
、sleep
方法需要時異步的sleepFirst
解題思路
- 采用 ES6 的 class,來實作,封裝對象
_LazyMan
- 提供一系列方法,比如
。eat
sleep
異步方法采用sleepFirst
和Promise
實作setTimeout
- 鍊式調用,考慮到其中含異步方法,采用任務隊列及 ES6 的
實作。每次調用都往隊列中加入方法,然後循環調用任務隊列,而循環中通過異步實作異步的方法,保證正确。async wait
具體實作
class _LazyMan {
constructor (name) {
this.taskQueue = [];
this.runTimer = null;
this.sayHi(name);
}
run () {
if (this.runTimer) {
clearTimeout(this.runTimer);
}
this.runTimer = setTimeout(async () => {
for (let asyncFun of this.taskQueue) {
await asyncFun()
}
this.taskQueue.length = 0;
this.runTimer = null;
})
return this;
}
sayHi (name) {
this.taskQueue.push(async () => console.log(`Hi, this is ${name}`));
return this.run();
}
eat (food) {
this.taskQueue.push(async () => console.log(`Eat ${food}`));
return this.run();
}
sleep (second) {
this.taskQueue.push(async () => {
console.log(`Sleep ${second} s`)
return this._timeout(second)
});
return this.run();
}
sleepFirst (second) {
this.taskQueue.unshift(async () => {
console.log(`Sleep first ${second} s`)
return this._timeout(second);
});
return this.run();
}
async _timeout (second) {
await new Promise(resolve => {
setTimeout(resolve, second * 1e3);
})
}
}
// 測試
var LazyMan = name => new _LazyMan(name)
// lazyMan('Hank');
lazyMan('Hank').sleep(10).eat('dinner');
// lazyMan('Hank').eat('dinner').eat('supper');
// lazyMan('Hank').sleepFirst(5).eat('supper');