Passing multiple arguments and result of last function through pipe

北慕城南 提交于 2020-01-30 12:11:38

问题


I'm building a pipe with Ramda.js which accepts three arguments. The first function needs those three arguments, and it's result is used in the second function. However, the second function also needs one of the initial arguments. I cannot figure out the branching to build something like it.

In pseudocode style, I need something like this:

const composedFunction = R.pipe(
  firstFunction,
  secondFunction,
);

const firstFunction = (reusedArgument, secondArgument, thirdArgument) => someAnswer;
const secondFunction = (reusedArgument, someAnswer);

console.log(composedFunction({ foo: bar }, [5, 3, 4], [100, 12, 12]));

回答1:


I can think of a few solutions:

Wrap your pipe inside another function so that functions in your composition can still refer to the original parameters.

Here func2 accepts the output of func1 but also has access to the initial b parameter. Obviously func2 must be curried and be designed to accept its "data" as the last parameter (which is a tenet of Ramda and functional programming in general I'd say).

const func3 = (a, b, c) =>
  pipe(func1, func2(b))
   (a, b, c);

func3(10, 20, 30);

Other option, func1 returns an array which you can destructure in func2.

I don't think this is particularly nice but it is an option:

const func1 = (a, b, c) => [a + c, b];
const func2 = ([sum, b]) => sum * b;

const func3 = pipe(func1, func2);
func3(10, 20, 30);



回答2:


I think the simplest thing here is to not bother with Ramda's pipe function, which is not designed to handle such case, and just write it manually:

const func1 = (a, b, c) => `func1 (${a}, ${b}, ${c})`
const func2 = (a, d) => `func2 (${a}, ${d})`

const func3 = (a, b, c) => func2 (func1 (a, b, c), a)

console .log (func3 ('a', 'b', 'c'))

Ramda has recently been considering a way to make this easier for longer pipelines; even with that, though, the above is probably simpler for just a few functions.



来源:https://stackoverflow.com/questions/59213250/passing-multiple-arguments-and-result-of-last-function-through-pipe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!