12. 柯里化案例
leezozz 1/27/2023 js
# 柯里化案例
match使用正则表达式:/s匹配空白字符,/s+匹配任意多个空白字符,g全局匹配
''.match(/\s+/g) // 匹配空白字符
''.match(/\d+/g) // 匹配数字
const _ = require('lodash')
const match = _.curry(function(reg, str) {
return str.match(reg)
})
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 提取空白字符
const haveSpace = match(/\s+/g)
1
# 提取数字
const haveNumber = match(/\d+/g)
// console.log('haveSpace', haveSpace("hi hi")) // [ ' ' ]
// console.log('haveSpace', haveSpace("hihi")) // null
// console.log('haveNumber', haveNumber("123fere89")) // [ '123', '89' ]
// console.log('haveNumber', haveNumber("hihi")) // null
1
2
3
4
5
2
3
4
5
# 找出数组中还有空白字符的元素
const customFilter = _.curry(function(fn, arr) {
return arr.filter(fn)
})
const findSpace = customFilter(haveSpace)
console.log(customFilter(haveSpace, ['12', '3', 'cd f', 'r', 'oo p']))
console.log(findSpace(['cd f', 'r', 'oo p']))
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9