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

实现管道函数 #73

Open
Sunny-117 opened this issue Nov 3, 2022 · 4 comments
Open

实现管道函数 #73

Sunny-117 opened this issue Nov 3, 2022 · 4 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@bearki99
Copy link

function pipe(...funcs) {
  return function (value) {
    return funcs.reduce((currentValue, func) => func(currentValue), value);
  }
}

@veneno-o
Copy link
Contributor

veneno-o commented Mar 15, 2023

  • 楼上的方法只能单参传递
  • 不妨看看我的
function pipe(...args1){
    return function(...args2){
        if(args1.length === 0) return;
        if(args1.length === 1) return args1[0](...args2);
        return args1.reduce((a, b) => function(){
                return b(a(...args2))
        })()
    }
};

@kangkang123269
Copy link

  • 楼上没有考虑前一个值不是函数的情况呢
function pipe(...fns) {
    return function(...args) {
        if (fns.length === 0) return;
        if (fns.length === 1) return fns[0](...args);
        
        return fns.reduce((acc, fn) => {
            if (typeof acc === 'function') {
                acc = acc(...args);
                args = []; // 清空参数列表,因为之后的函数应该接收上一个函数的结果作为输入
            }
            return fn(acc); // 将上一步骤得到结果作为当前操作器输入
        });
    };
}

@Aurora-GSW
Copy link

function pipe(...fns) {
    return function (...args) {
        return fns.reduce((v, f2, i) => {
            if (typeof f2 !== 'function') {
                throw new TypeError(`${typeof f2} is not a function`)
            }
            return i ? f2(v) : f2(...v)
        }, 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

5 participants