面试题 LazyMan 的Rxjs完成体式格局

媒介

笔者昨天在做某公司的线上笔试题的时刻遇到了末了一道关于怎样完成LazyMan的试题,问题以下

完成一个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
以此类推。

鉴于时候的缘由只可惜本人当时并没写出来,我当时脑海里实在看到提意就晓得要用到行列、Promise等异步操纵。然后我查阅了网上的材料彷佛关于这个LazyMan的完成体式格局倒不少,就申明这道题实在蛮有意思的,但大多都是关于Promise或setTimeout的完成,并没有Rxjs的完成体式格局,所以我就用一些操纵符完成了这个LazyMan

class LazyManModel {
    queue: { timeout: number, fn: Function }[] = []
    constructor() {
        setTimeout(() => {
            from(this.queue).pipe(
                map(e => {
                    if (e.timeout) return of(e).pipe(delay(e.timeout * 1000));
                    return of(e)
                }),
                concatAll()
            ).subscribe(value => {
                value.fn()
            })
        })
    }

    sleep(time: number): this {
        this.queue.push({
            timeout: time,
            fn: () => { console.log(`Wake up after ${time}`) }
        })
        return this
    }

    eat(foot: string): this {
        this.queue.push({
            timeout: null,
            fn: () => { console.log(`Eat ${foot}~`) }
        })
        return this
    }

    sleepFirst(time: number): this {
        this.queue.unshift({
            timeout: time,
            fn: () => { console.log(`Wake up after ${time}`) }
        })
        return this
    }

    exported(): (name: string) => this {
        return (name): this => {
            this.queue.push({
                timeout: null,
                fn: () => { console.log(`Hi! This is ${name}!`) }
            })
            return this
        }
    }
}

示例

const LazyMan = new LazyManModel().exported();
LazyMan('Hank').eat('foot').eat('ping').sleep(10).eat('pizza').sleepFirst(5)

关于setTimeout

我在constructor组织函数里使用了setTimeout是因为,在挪用的时刻是链式的,其作用域一向都在统一客栈,而setTimeout里则是把定阅的要领放到的末了一个栈实行

    原文作者:_John
    原文地址: https://segmentfault.com/a/1190000017842510
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞