zoukankan      html  css  js  c++  java
  • 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()
        }
    }
    
  • 相关阅读:
    MogileFS的实现和bug解决
    MogileFS介绍
    SAMBA
    NFS
    测试DNS服务的命令
    DNS中的AC、rndc、智能DNS解析和基础排错
    DNS的主从、子域授权和转发服务器
    DNS域名记录
    DNS
    JavaScript设计模式与开发实践随笔(二)
  • 原文地址:https://www.cnblogs.com/shineyao/p/7499881.html
Copyright © 2011-2022 走看看