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

【前端成长之路】实现柯里化函数 #3

Open
AmamiyaCx opened this issue Sep 3, 2022 · 0 comments
Open

【前端成长之路】实现柯里化函数 #3

AmamiyaCx opened this issue Sep 3, 2022 · 0 comments

Comments

@AmamiyaCx
Copy link
Owner

function curry(fn) {
    return function curries(...args) {
        if (args.length >= fn.length) {
            return fn.apply(this, args);
        } else {
            return function (...args2) {
                return curries.apply(this, [...args, ...args2])
            }
        }
    }
}
// 示例
const sum = (a, b, c) => {
    return a + b + c;
}

const cy = curry(sum);

console.log(cy(1, 2, 3)); // 6
console.log(cy(1, 2)(3)); // 6
console.log(cy(1)(2, 3)); // 6
console.log(cy(1)(2)(3)); // 6

以**cy(1)(2)(3)**为示例简单描述下代码的执行过程:

  • 首先第一步,将sum函数传入柯里化函数
  • 然后执行cy(1)
  • 此时的args长度为1,不满足条件走到了else分支,else分支又返回了curries柯里化函数
  • 接着执行cy(2)
  • 此时args还是1,接着走else分支,返回根据返回的函数拼接第一次和这一次的参数[1,2]
  • 最后执行cy(3),因为args长度还是1,还是走else分支,此时...args为3,...args2为[1,2],拼接上执行curries函数,然后发现[1,2,3]的长度满足大于等于sum函数的参数长度的,于是执行sum函数,返回1+2+3的结果
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