柯里化(英语:Currying)
- 是把接收多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数
- 并且返回接收余下的参数而且返回结果的新函数的技术
作用:
- 可以固定相同参数,实现函数调用传参的简单化
- 可以让参数复用
例子:通过传递参数返回一个完整网址
- 完整网址分为三部分
- 协议 https、http protocol
- 域名 www.baidu.com domain
- 端口号 :8080 port
function address(protocol, domain, port){
return protocol + domain + port
}
//问题:通过这种形式传递参数,第一个参数其实可以固定化,希望的是传递一次给所有的地址都可以使用
let result1 = address('https://', 'www.jd.com', ':8080')
console.log(result1)
let result2 = address('https://', 'www.mi.com', ':80')
console.log(result2)
函数柯里化:需要把固定的参数放在最外层,如果需要修改协议,只需要修改外层的,其他地方都可以改变
function addCurrying(protocol){
return function(domain){
return function(port){
return protocol + domain + port
}
}
}
const currying = addCurrying('https://')
const result1 = currying('www.jd.com')(':8080')
console.log(result1)
const result2 = currying('www.mi.com')(':80')
console.log(result2)
函数柯里化案例
假设你是一个商家,要出售商品,为了卖出去更多的商品,今天决定打9折进行售卖,我们可以使用以下函数进行折扣后的售出价格计算
// 实现了柯里化
function discCurrying(disc){
return function(price){
return price * (1 - disc)
}
}
const goodsPrice = discCurrying(.5)
const total1 = goodsPrice(1000)
const total2 = goodsPrice(3000)
console.log(total1, total2)