柯里化函数

柯里化函数 -- 期待固定数量参数

//固定参数     

function fixedCurryParams(fn) { var _args = [].slice.call(arguments, 1) return function () { var newArgs = _args.concat([].slice.call(arguments, 0))    return fn.apply(this, newArgs) } }
  //期望参数 参数没给够就一直期望 可以累积参数
function curry(fn, length) { var length = length || fn.length return function () { if (arguments.length < length) { var combined = [fn].concat([].slice.call(arguments, 0)) return curry(fixedCurryParams.apply(this, complay), length - arguments.length) } else { return fn.apply(this, arguments) } } }

测试

 function add(a, b, c, d) {
            return a + b + c + d;
        }

 var newAdd = fixedCurryParams(add, 1, 2)
 var lastAdd = curry(add)
  console.log(newAdd(1,2,3,4))//10   console.log(newAdd(
1, 2)) // 6 var a = lastAdd(1)(2)(3)(5) console.log(a) //11

 应用实例

function ajax(type, url, data) {
    var xhr = new XMLHttpRequest()
    xhr.open(type, url, true)
    xhr.send(data)      
}

//通常会这么写
ajax("post", 'www.test.com', 'name=zhangsan')
ajax("post", 'www.test.com', 'name=wnagwu')
ajax("post", 'www.test.com', 'name=lisi')

//使用柯里化后 可以积累参数
var ajaxCurry = curry(ajax)
var post  = ajaxCurry('post')
post('www.test.com', 'name='zhangsan')

var postParams = post('www.test.com')
postParams('name=zhangsan')
postParams('name=lisi')

 

转载于:https://www.cnblogs.com/CoderZX/p/11243722.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值