Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript中的函数柯里化 #4

Open
FIGHTING-TOP opened this issue Nov 10, 2020 · 0 comments
Open

JavaScript中的函数柯里化 #4

FIGHTING-TOP opened this issue Nov 10, 2020 · 0 comments
Assignees
Labels
柯里化 js函数柯里化

Comments

@FIGHTING-TOP
Copy link
Owner

FIGHTING-TOP commented Nov 10, 2020

简介

当我们在读Vue源码到时候会发现,在它的 _update 实例中就用到了函数柯里化,(createPatchFunction方法)有兴趣的可以去看一下。
柯里化(Currying)是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数而且返回结果的新函数的技术
在《Mostly adequate guide》中,这样总结了 Currying ——只传递给函数一部分参数来调用它,让它返回一个函数去处理剩下的参数
Currying 是函数式编程的一种实现,可以给我们的编程带来便利。那 Currying 函数到底长什么样呢?请往下看,我们根据它的概念自己来写一个柯里化函数

实现

// 如何实现 add(1,2)  === add(1)(2)
let add = (...args) => {
    return args.length === 1 ? a => a + args[0] : args[0] + args[1]
}

这个似乎有一点接近柯里化的意思,但并不是真正的Currying,我们应该做到 add(1,2,3,,,) === currying(add)(1,2,3,,,) 才能算是真正的柯里化函数,OK,我们继续往下来,

let add = (...args) => args.reduce((a,b)=>a+b)

let currying = (fn)=>{
    return function(...args){
        return fn.apply(this, args)
    }
}
// add(1,2,3,,,) === currying(add)(1,2,3,,,) 

还有人这么玩,可以参考下

let currying = (fn) => {
    var args = [].slice.call(arguments, 1)
    return function() {
        var newArgs = args.concat([].slice.call(arguments))
        return fn.apply(this, newArgs)
    }
}

let addCurry = currying(add, 1, 2);
addCurry() // 3

addCurry = currying(add, 1);
addCurry(2) // 3

addCurry = currying(add);
addCurry(1, 2) // 3

实际上这个实现方法利用闭包的原理,有时间给大家做个对比,

分析

可以看到,实际上柯里化函数并不算难,要想实际运用在我们的开发中,需要我们花点小心思~

@FIGHTING-TOP FIGHTING-TOP added the 柯里化 js函数柯里化 label Nov 10, 2020
@FIGHTING-TOP FIGHTING-TOP self-assigned this Nov 10, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
柯里化 js函数柯里化
Projects
None yet
Development

No branches or pull requests

1 participant