柯里化
一种将使用多个参数的一个函数转换成一系列使用一个参数的函数的技术
function curry(fn, length = fn.length) {
let args1 = Array.prototype.slice.call(arguments, 2)
return function () {
let context = this;
let args2 = Array.prototype.slice.call(arguments, 0)
let newArgs = args1.concat(args2);
if (newArgs.length >= length) {
return fn.apply(context, newArgs)
} else {
return curry(function () {
let args3 = Array.prototype.slice.call(arguments, 0)
fn.apply(context, newArgs.concat(args3))
}, length - newArgs.length)
}
}
}
作用:参数复用,比如有个根据行政区查询身份证开头的函数
function query(province, city, county) {
console.log(province, city, county, '的身份证号开头是xxx')
}
query('四川', '成都', '锦江')
query('四川', '成都', '郫县')
query('四川', '成都', '成华')
通过参数复用
let queryByCounty = curry(query)('四川')('成都')
queryByCounty('锦江')
queryByCounty('郫县')
queryByCounty('成华')
偏函数(也称局部应用 Partial application)
指固定一个函数的一些参数,然后产生另一个更小元的函数的技术。可以理解为不彻底的柯里化
function partial(fn, length = fn.length) {
let args1 = Array.prototype.slice.call(arguments, 2)
return function () {
let context = this;
let args2 = Array.prototype.slice.call(arguments, 0)
let newArgs = args1.concat(args2);
return fn.apply(context, newArgs)
}
}
Function.prototype.bind 实际上就使用了偏函数,参数可以分两次传递
function log(name, age){
console.log('个人信息:', name, age)
}
log.bind(null, '张三')(24)
网友评论