函数柯里化 Currying

什么是函数柯里化

是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数而且返回结果的新函数的技术

实际应用

1
2
3
4
5
6
7
8
9
// 函数封装后
function check(reg, txt) {
return reg.test(txt)
}

// 即使是相同的正则表达式,也需要重新传递一次
console.log(check(/\d+/g, 'test1')); // true
console.log(check(/\d+/g, 'testtest')); // false
console.log(check(/[a-z]+/g, 'test')); // true

Currying后

1
2
3
4
5
6
7
8
9
10
11
12
13
14

function curryingCheck(reg) {
return function (txt) {
return reg.test(txt)
}
}

// 正则表达式通过闭包保存了起来
var hasNumber = curryingCheck(/\d+/g)
var hasLetter = curryingCheck(/[a-z]+/g)

console.log(hasNumber('test1')); // true
console.log(hasNumber('testtest')); // false
console.log(hasLetter('21212')); // false

经典面试题

1
2
3
4
5
6
7
写一个add函数 要求: 
add(1)(2) == 3
add(1)(2)(3) == 6;
add(1, 2)(3) == 6;
tip:
由add(1)(2)(3)可知 add(1)(2) 应该是返回函数的
但是又add(1)(2) == 3 ,可知 里面有隐式转换,重写toString()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function add() {
//空参数默认为0
//这个数组利用了闭包的特性,所有加数都会push进这个数组
const _args = arguments.length ? [...arguments] : [0];

function _adder() {
_args.push(...arguments || 0)
return _adder
}
//隐式转换时调用toString()
_adder.toString = function () {
return _args.reduce((a, b) => a + b)
}
//返回一个函数是一定的
return _adder
}
console.log(add(1, 2)(3, 4).toString());