fe-learning icon indicating copy to clipboard operation
fe-learning copied to clipboard

微信面试题 LazyMan

Open metroluffy opened this issue 5 years ago • 0 comments

微信面试题 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 lazyMan {
    constructor (name) {
        this.name = name
        this.sleepTime = 0
        this.sleepFirstTime = 0
        this.taskList = []
        console.log(`Hi I am ${this.name}`);
        setTimeout(() => {
            this.next()
        }, 0)
    }
    next() {
        var fn = this.taskList.shift();
        fn && fn();
    }
    eat (f) {
        var that = this;
        var fn = (function (n) {
            return function () {
                console.log(`I am eating ${n}`)
                that.next();
            }
        })(name);
        this.taskList.push(fn);
        return this;
    }
    sleep (time) {
        var that = this;
        var fn = (function (t) {
            return function () {
                setTimeout(() => {
                    console.log(`等待了${t}秒...`)
                    that.next();
                }, t * 1000);  
            }
        })(time);
        this.taskList.push(fn);
        return this;
    }
    sleepFirst(time) {
        var that = this;
        var fn = (function (t) {
            return function () {
                setTimeout(() => {
                    console.log(`等待了${t}秒...`)
                    that.next();
                }, t * 1000);  
            }
        })(time);
        this.taskList.unshift(fn);
        return this;
    }
}
function LazyMan(name) {
    return new LazyManClass(name);
}

metroluffy avatar May 31 '20 09:05 metroluffy