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

26. 实现sum(1,2,3)==sum(1)(2)(3) #27

Open
fedono opened this issue Nov 3, 2020 · 1 comment
Open

26. 实现sum(1,2,3)==sum(1)(2)(3) #27

fedono opened this issue Nov 3, 2020 · 1 comment

Comments

@fedono
Copy link
Owner

fedono commented Nov 3, 2020

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

解法

const curry = fn => {
    const len = fn.length;
    return function curried(...args) {
        if (args.length === len) {
            return fn.apply(null, args);
        }
        return (..._args) => {
            return curried.apply(null, [...args, ..._args]);
        };
    };
};

const sum = (x, y, z) => x + y + z;
const add = curry(sum);

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

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

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

// 6
add(1)(2)(3);

参考

  • 第 84 题:请实现一个 add 函数

    这题里面有 add(1) // 1 ,也就是无论是几个参数都会进行计算。但是看了下所有网友给的题解,都是在函数中来接收参数,然后使用toString 方法来计算总和,那怎么才能去拿到函数的toString计算的值呢?使用 add(1) 返回的是[Function add]这种格式啊

@fedono
Copy link
Owner Author

fedono commented Sep 9, 2023

换个更简单一点的

function add(...args) {
    if (args.length === 3) {
        return Array.from(args).reduce((pre, curr) => {
            return pre + curr
        }, 0)
    } else {
        return function curry(...argus) {
            /* 
            1. 这里的 apply 很重要,把参数转换成数组,如果只是 add() 调用,上面的 args.length 就一直是 1,这个还没搞明白是为啥
            2. 这里很重要的一点,就是将参数聚合起来
            */
            return add.apply(null, [...argus, ...args])
        }
    }
}

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