JS编程实现-currying(柯里化)

// 参数先给你存着,等你没参数了再一起给你
let currying = function (fn) {
    let argArr = []
    return function () {
        if ( arguments.length === 0) {
            // 卡了很久是因为不熟悉apply的参数列表跟fn的关系
            // 虽然argArr是[1,2],但用apply的数组是参数列表,costTotal加参数只取第一个元素1
            return fn.call(this, argArr)
        } else {
            Array.prototype.push.apply(argArr,arguments)
        }
    }
}

// 无参数时触发,使用之前存的参数
let costTotal = (function () {
    let sum = 0
    // 注意下面的匿名函数加不加参数取决于fn用的是call还是apply
    return function (costDay) {
        // apply用:for(let i=0;i<arguments.length;i++){,不传costDay
        for(let i=0;i<costDay.length;i++){
            sum += costDay[i]
            console.log(`costDay${i+1}:`,costDay[i]);
        }
        console.log('sum',sum);
        return sum
    }
})()

let costCurrying = currying(costTotal)

costCurrying(10)
costCurrying(20)
costCurrying()

运行结果:
测试结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值