shineYao

middleware#52

错误做法

这道题还是挺有意思的,一开始自己的做法是这样的

const app = {
    fns: [],
    callback(ctx) {
        console.log(ctx)
    },

    use(fn) {
        this.fns.push(fn);
    },
    go(ctx) {
        this.fns.push(this.callback)
        const loop = (fns, idx) => {
            const next = fns[idx]
            if(next === this.callback) {
                next(ctx)
            } else {
                next(ctx, ()=> loop(fns, ++idx))
            }

        }
        loop(this.fns, 0)
    }
}

简单测试了下也没问题,但是提交上去出现错误,

后来在讨论区看到是因为如果go和use交替的场景我这里的this.fns.push(this.callback)肯定是不能满足的,简单修改通过,

const app = {
    fns: [],
    callback(ctx) {
        console.log(ctx)
    },

    use(fn) {
        this.fns.push(fn);
    },
    go(ctx) {
        const loop = (fns, idx) => {
            const next = fns[idx]
            if(next === undefined) {
                this.callback(ctx)
            } else {
                next(ctx, ()=> loop(fns, ++idx))
            }

        }
        loop(this.fns, 0)
    }
}

但总觉得这实现不够优雅,这个还不错:

const app = {
    fns: [],
    callback(ctx) {
        console.log(ctx)
    },

    use(fn) {
        this.fns.push(fn);
    },
    go(ctx) {
        const start = this.fns.reduceRight((next, iter) => () => iter(ctx, next) , () => this.callback(ctx))
        start()
    }
}

posted on 2017-09-10 00:05  shineYao  阅读(80)  评论(0编辑  收藏  举报

导航