JS柯里化的理解&其弊端

Currying小结

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

  2. 柯里化的好处:

    • 参数复用(利用闭包和高阶函数的特性)
    • 延迟执行 (例如JS中的bind方法,实现的机制就是currying)
  3. 性能瓶颈以及lamda.jsuncurrying

    • 性能:
    image-20220331013622679
    • lamda:https://ithelp.ithome.com.tw/articles/10280237
    • uncurring: https://medium.com/@jnkrtech/currying-and-uncurrying-in-javascript-and-flow-98877c8274ff
  4. 实现一个通用的柯里化函数

参考资料:

  • https://www.bilibili.com/video/BV1EF411B7we?p=1
  • https://ithelp.ithome.com.tw/articles/10279415

参数复用

1.拼接URL

没有柯里化

function getUrl(scheme, host, path) {
    return `${scheme}:/${host}/${path}`
}
join(`https`,`taobao.com`, `user1`)
join(`https`,`taobao.com`, `user2`)
join(`https`,`taobao.com`, `user3`)
复制成功
1
2
3
4
5
6

部分柯里化

const getUrl = (scheme) => {
    return (host,path) => `${scheme}:/${host}/${path}` 
}
const join = getUrl(`https`)
join(`jd.com`, `user`)
join(`taobao.com`, `user1`)
join(`taobao.com`, `user2`)
join(`taobao.com`, `user3`)
复制成功
1
2
3
4
5
6
7
8

柯里化

const getUrl = (scheme) => {
    return (host) => {
        return (path) => `${scheme}:/${host}/${path}`
    }
}
const join1 = getUrl(`https`)
const join2 = join1(`taobao.com`)
getUrl(`https`)('jd.com')('user')
join2('user1')
join2('user2')
join2('user3')
复制成功
1
2
3
4
5
6
7
8
9
10
11

2.正则校验函数

没有柯里化

function check(regExp, data) {
    return regExp.test(data)	// result: true or false
}
console.log(check(/\d+/g,10))
console.log(check(/\d+/g,'emo'))
复制成功
1
2
3
4
5

柯里化

function check(regExp) {
    return (data) => regExp.test(data)
}
let hasNumber = check(/\d+/g)
console.log(hasNumber(10))
console.log(hasNumber('emo'))
复制成功
1
2
3
4
5
6

延迟执行

实现bind

// test driven
let obj = {name:'re0', age:15}
function fn() {
    console.log(this.name)
    return `${this.name},${this.age}`
}
let f = fn.myBind(obj)
f()

//实现
Function.prototype.myBind = (ctx, ...args) => {
	return () => {
        return this.apply(ctx, args)
        // return this.call(ctx, ...args)
        
    }
}
复制成功
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

手写Currying

待定

晓露寝安浅云逍遥十漾轻拟