【问题标题】:Functional way to execute a sub-array with Ramda使用 Ramda 执行子数组的函数式方法
【发布时间】:2016-09-09 15:43:48
【问题描述】:

是否有更实用的方法来执行以下操作,也许使用 Ramda?

var time = 100;

sequenceInstruments.forEach(function(instrument){
    if(instrument.on)
    {
       playInstrument(time, instrument.duration);
    }
})

【问题讨论】:

  • 请注意,如果没有 else 分支,您可以避免使用 if 语句和 Array.prototype.filter。只需将mapfilter 组合在一起即可。如果你也想避免中间数组,只需使用它们的转换器实现。
  • "执行一个子数组" ?

标签: javascript functional-programming ramda.js


【解决方案1】:

通过仅以无点方式使用 Ramda 中的函数,您的示例将如下所示。

const play = R.forEach(R.when(R.prop('on'),
                              R.compose(R.partial(playInstrument, [time]),
                                        R.prop('duration'))))
play(sequenceInstruments)

但我经常认为,将其拨回一点可能会更好,因为使用匿名函数可能会使代码更具可读性并更清楚地传达意图。

const play = R.forEach(R.when(R.prop('on'), i => playInstrument(time, i.duration)))

play(sequenceInstruments)

【讨论】:

    【解决方案2】:

    虽然我同意 Scott Christopher 的观点,但如果您有兴趣开发无点版本,并且如果您有“希望time 成为您最终函数的参数,Ramda 提供了一个可能有帮助的函数,useWith。 (还有一个相关的函数,converge 适用于稍有不同的情况。)这取决于你的 playInstrument 函数被柯里化:

    const play = R.useWith(R.forEach, [
      playInstrument, 
      R.compose(R.pluck('duration'), R.filter(R.prop('on')))
    ]);
    
    play(100, sequenceInstruments);
    

    您可以在 Ramda REPL 上看到这一点。

    【讨论】:

      【解决方案3】:

      我同意@ftor:filter 将允许您以更线性的方式编写代码,从而产生完全可读的无点代码。

      const play = pipe(
          filter(prop('on')),           // take only the instruments that are 'on'
          map(prop('duration')),        // take the duration of each of those
          forEach(playInstrument(100))  // play'm all
      );
      
      play(sequenceInstruments);
      

      这是假设 playInstruments 已经被柯里化了。

      使用lodash/fp 的速记,您甚至可以这样做:

      const play = pipe(
          filter('on'),
          map('duration'),   
          forEach(playInstrument(100))
      );
      

      【讨论】:

      • 对于漂亮的简单管道来说是加分项,对于可怕的重载“速记”来说是减分项。
      • @ScottSauyet 我了解你的观点。 Ramda 有一种“纯粹”的功能方法,而人们可能会称 Lodash 的方法更“实用”。我不会太容易害怕;)
      • 也许,但这也是 jQuery 多年来一直声称的。不知何故,它似​​乎在所有的重量下沉没。无论如何,这是一个不错的解决方案!
      猜你喜欢
      • 2018-03-13
      • 1970-01-01
      • 2018-03-16
      • 2017-10-07
      • 1970-01-01
      • 1970-01-01
      • 2017-05-10
      • 2015-02-05
      • 2018-11-12
      相关资源
      最近更新 更多