问题
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