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()
        }
    }
    
  • 相关阅读:
    js难点之闭包理解
    rank() | dense_rank() | row_number() over(PARTITION BY sex order by age desc ) 的区别
    浏览器名称和版本判断
    Cookie与Session的初探
    ASP.NET基础系列
    ECharts使用
    java-保留x个小数位
    HttpServletResponse和HttpServletRequest
    java-socket通信
    java-序列化
  • 原文地址:https://www.cnblogs.com/shineyao/p/7499881.html
Copyright © 2011-2022 走看看