学习笔记——函数柯里化

179 阅读1分钟

1.什么是函数柯里化? 当一个函数有多个参数的时候,先传递一部分参数调用它 然后返回一个新的函数接收剩余的参数,返回结果

列子(假如要比较这件商品和其他商品之间的差价)

`
//比较商品差价
//goods is number
//otherGoods is Array
function comparePrice(goods,otherGoods) {
    let res = []
    for(let i = 0; i<otherGoods.length;i++) {
     res.push(otherGoods[i] > goods ? '贵' : '便宜')
    }
    return res
 }
`

image.png 将代码函数柯里化后

const comparePrices = (price) => {
    return function(priceList) {
    let res = []
        for(let i = 0; i<priceList.length; i++) {
            res.push(priceList[i] > price ? "贵" : "便宜")
        }
        return res
    }
}

image.png

柯里化函数通用封装(将一个函数变成柯里化的函数)

实现逻辑,将一个函数传递进去,判断该函数的所需的参数个数和实际传递的参数个数是否一致?

如果一致:则执行该函数,返回函数结果。

如果不一致:返回一个新的接受剩余参数个数的函数。

function curry(fn) {
    //...args 剩余参数
    return function curriedFn(...args) {
        //判断实参和形参的个数
        if(args.length < fn.length) {
            return function() {
                return curriedFn(...args.concat(Array.from(arguments)))
            }
        }
        //满足时
        return fn(...args)
    }
}

验证代码

const myFn = curry(comparePrice)
console.log(myFn(100)([50,120,130,30,20]))
console.log(myFn(100,[50,120,130,30,20]))
console.log(myFn(6))

image.png

总结

函数柯里化的作用能让某部分函数的职责变的单一,可以通过不断地组合形成更复杂但内部又不会过度耦合的函数