函数柯里化、偏函数、惰性函数

  • 柯里化:将n元函数转换成n个一元函数 | 将一个多参数的函数转成多个单参数的函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function add(a, b, c, d) {
return a + b + c + d
}
function curry(fn, len) {
var len = len || fn.length
var func = function (fn) {
var _arg = [].slice.call(arguments, 1)
console.log('_arg: ', _arg);
return function () {
var newArgs = _arg.concat([].slice.call(arguments))
return fn.apply(this, newArgs)
}
}
return function () {
// 单次参数传入个数
var argLen = arguments.length
// 是否满足柯里化参数要求,不满足继续递归柯里化
if (argLen < len) {
var formateArr = [fn].concat([].slice.call(arguments))
return curry(func.apply(this, formateArr), len - argLen)
} else {
// 满足参数要求情况下最后执行
return fn.apply(this, arguments)
}
}
}

var add2 = curry(add)
var res = add2(1)(2)(3)(4)
  • 偏函数:将n元函数转换成n-x元参数 | 固定一个函数的一个或多个参数
1
2
3
4
5
6
7
8
Function.prototype.partial = function(){
var _self = this,
_args = [].slice.call(arguments)
return function(){
var newArgs = _args.concat([].slice.call(arguments))
return _self.apply(this,newArgs)
}
}
  • 惰性函数
1
2
3
4
5
6
7
8
9
10
11
var getTimeStamp = function(){
var timeStamp = new Date().getTime()

getTimeStamp = function(){
return timeStamp
}
return getTimeStamp()
}
console.log(getTimeStamp())
console.log(getTimeStamp())
console.log(getTimeStamp())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function test(val){
switch(val){
case 1:
test = function(){
console.log('惰性函数1')
}
break;
case 2:
test = function(){
console.log('惰性函数2')
}
break;
case 3:
test = function(){
console.log('惰性函数3')
}
break;
}
return test()
}
test(1)
test(2)