Ramda pipe with dynamic function

丶灬走出姿态 提交于 2019-12-11 04:22:35

问题


var arr = [functionA(), functionB(), functionC()]
var data = { /** some data */ }

How can I dynamically add the functions from the arr list and add it to ramda pipe.

Expected code:

const newFn = pipe(functionA, functionB, functionC)

newFn(data)

回答1:


You can use apply:

const buildPipe = apply(pipe);
const add3 = buildPipe([inc, inc, inc]);
const add4 = buildPipe([inc, inc, inc, inc]);

console.log(add3(1));
console.log(add4(2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
<script>const {apply, pipe, inc} = R;</script>



回答2:


Just use the es6 spread operator which will spread out the array items as arguments to the pipe function.

Also, don't call your functions in the array unless they are returning a function that you want :)

const arr = [functionA, functionB, functionC]
const data = { /** some data */ }

const newFn = pipe(...arr)

newFn(data)


来源:https://stackoverflow.com/questions/55114642/ramda-pipe-with-dynamic-function

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