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

JS实现函数柯里化 #15

Open
akeymo opened this issue Feb 16, 2020 · 0 comments
Open

JS实现函数柯里化 #15

akeymo opened this issue Feb 16, 2020 · 0 comments

Comments

@akeymo
Copy link
Owner

akeymo commented Feb 16, 2020

所谓函数柯里化,就是把一个接受多个参数的函数转变成接受单一参数(最初的函数的第一个参数)的函数,并且返回接受余下的参数而且返回结果的函数。

假设有一个进行加法运算的函数:

function add(a, b) {
    console.log(a + b);
}

然后我们有实现柯里化的函数叫curry,所达到的效果应该包括:

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

const addRes = currying(add, 1);
addRes(5); // 6

实现以上效果的curry函数的实现方法如下:

function currying(fn, ...args) {
    //  如果传入的参数数量大于等于传入函数所需的参数,直接返回结果
    if (args.length >= fn.length) {
        return fn(...args);
    }

    return function (...args2) {
        return currying(fn, ...args, ...args2);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant