【问题标题】:Ramda pipe with dynamic function具有动态功能的 Ramda 管道
【发布时间】:2019-03-12 05:22:06
【问题描述】:
var arr = [functionA(), functionB(), functionC()]
var data = { /** some data */ }

如何从 arr 列表中动态添加函数并将其添加到 ramda 管道。

预期代码:

const newFn = pipe(functionA, functionB, functionC)

newFn(data)

【问题讨论】:

    标签: javascript ramda.js


    【解决方案1】:

    你可以使用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>

    【讨论】:

    • 在另一篇文章中提到,原生function.apply 也将与使用R.apply 函数一样工作。
    【解决方案2】:

    只需使用 es6 扩展运算符,它将数组项作为管道函数的参数展开。

    另外,不要在数组中调用你的函数,除非它们返回你想要的函数:)

    const arr = [functionA, functionB, functionC]
    const data = { /** some data */ }
    
    const newFn = pipe(...arr)
    
    newFn(data)
    

    【讨论】:

      猜你喜欢
      • 2019-10-04
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      • 2017-09-21
      相关资源
      最近更新 更多