前端面試中的LazyMan

妙筆生花發表於2018-03-19

實現一個LazyMan,可以按照以下方式呼叫:
LazyMan(“Hank”)輸出:
Hi! This is Hank!

LazyMan(“Hank”).sleep(10).eat(“dinner”)輸出
Hi! This is Hank!
//等待10秒..
Wake up after 10
Eat dinner~

LazyMan(“Hank”).eat(“dinner”).eat(“supper”)輸出
Hi This is Hank!
Eat dinner~
Eat supper~

LazyMan(“Hank”).sleepFirst(5).eat(“supper”)輸出
//等待5秒
Wake up after 5
Hi This is Hank!

Eat supper
以此類推。

題目解析:看起來是鏈式呼叫並且有流程控制其中sleepFisrt要在所有函式之前執行。大致的思路是建立一個任務佇列,將每一項任務(輸出名字、吃飯、睡覺)都放進佇列裡按順序執行。程式碼如下:

function LazyMan(name){
    let _lazyMan = {
        sayHi : function () {
            queue.push(() => {
                    console.log('Hi! This is'+name)
                    this.next();
            })
        },
        eat : function (food) {
            queue.push(() => {
                    console.log('Eat '+food)
                    this.next();
            })
            return this;
        },
        sleep : function (second) {
            queue.push(() => {
                setTimeout(() => {
                    console.log("wake  up after "+ second + "秒")
                    this.next();
                },second * 1000)
            })
            return this;
        },
        sleepFirst : function (second) {
            queue.unshift(() => {
                setTimeout(() => {
                    console.log("wake  up after "+ second + "秒")
                    this.next();
                },second * 1000)
            })
            return this;
        },
        next : function () {//函式依次執行
            let fn = queue.shift();
            fn && fn();
        }
    }
    let queue = [];//存放函式的任務佇列
    _lazyMan.sayHi();//將打招呼放進佇列
    setTimeout(function () {//開始執行任務佇列的裡的函式
        _lazyMan.next();
    })
    return _lazyMan;
}

// LazyMan("kakao")
// LazyMan("kakao").eat("apple").eat("banana")
// LazyMan("kakao").sleep(3).eat("apple")
// LazyMan("kakao").sleepFirst(3).eat("apple")
複製程式碼

相關文章