url地址拼接:
<!-- 利用函数柯里化的特性:参数复用,实现了URL地址拼接的功能 -->
<script>
function uri(protocol){
return function (hostname,path) {
return `${protocol}${hostname}${path}`
}
}
let curryUri = uri('https://')
// 每一次拼接的时候就只需要调用一次‘protocol这个属性’
console.log(curryUri('www.baidu.com/','index.html'));
console.log(curryUri('www.sina.com/','about.html'));
参数复用:
//函数柯里化:把原本接收所有参数的函数,转换为只接收部分参数的函数,并返回一个新的函数,该函数可以接收剩余的参数,并返回最终结果
// 特性:1. 参数的延迟调用; 2. 参数复用
// 正常的函数
function add(x, y) {
return x + y;
}
console.log(add(2, 3));
// 函数柯里化
function add1(x) {
return function add2(y) {
return x + y
}
// 后续拼接很像vue代理proxy(返回一个新的promise)
return function add2(s) {
return x + s
}
return function add2(z) {
return x + z
}
}
add1(8)(2)
console.log(add1(8)(2));
console.log(add1(8)(7));
console.log(add1(8)(12));
封装正则验证:
<script>
// 设置一个正则对象:::用于后续验证使用
const config = {
baseUrl: 'http://localhost:8888',
nameReg: /^[0-9a-z]\w{4,10}$/,
pwdReg: /^\w{4,10}$/,
nickReg: /^.{3,8}$/
}
console.log(config.nameReg);
/*
函数柯里化实现封装升级(eg:正则账号密码)
*/
// 1.正常情况下封装:调用一次,每次传俩参,较为麻烦
function test(reg, str) {
return reg.test(str)
}
test(config.nameReg, 12345)
test(config.pwdReg, 'abcde')
// test(config.baseUrl,'?')
// test(config.nickReg,'?')
console.log(test(config.nameReg));
// 2.(函数科里化封装)就很丝滑了
function test(reg) {
return function (str) {
return reg.test(str)
}
}
// 传入不同的正则,得到不同的测试结果
let a = test(config.nameReg)
let b = test(config.pwdReg)
let c = test(config.baseUrl)
let d = test(config.nickReg)
/*个人观点: a,b,c,d:返回值都是
ƒ (str){
return reg.test(str)
} ,
也就意味着a, b, c, d就是一个方法,待调用,所以
->->-> a('要验证的str')
*/
console.log(a, b, c, d);
var sss = '4'
console.log(a(sss), b('qwrtgy'));
// 所以你学'废'了吗???
</script>
打印结果: