简体   繁体   English

用Ramda执行子数组的功能方法

[英]Functional way to execute a sub-array with Ramda

Is there a more functional way of doing the below, perhaps with Ramda? 是否有可能使用Ramda进行以下操作时更具功能性的方式?

var time = 100;

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

By only utilising functions from Ramda in a point-free manner your example would look something like this. 通过仅以无点方式使用Ramda中的函数,您的示例将如下所示。

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

However I often think it can be better to dial it back a little, where the use of an anonymous function could perhaps make the code more readable and convey the intent more clearly. 但是,我经常认为最好回拨一下,在这种情况下使用匿名函数可能会使代码更具可读性,并更清楚地传达意图。

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

play(sequenceInstruments)

While I agree with Scott Christopher that the point-ful solution is easier to understand than any points-free version you're likely to come up with, if you are interested in developing a point-free version, and if you'd like time to be a parameter to your final function, Ramda offers a function that might help, useWith . 虽然我与斯科特克里斯托弗同意点FUL的解决方案是很容易,任何自由点的版本,你很可能会拿出,如果你有兴趣开发一个免费的点对点版本了解,如果你想time作为最终功能的参数, useWith提供了可能useWith的功能useWith (There's also a related function, converge useful for slightly different circumstances.) This depends upon your playInstrument function being curried: (还有一个相关的函数,可以converge用于稍微不同的情况。)这取决于您的playInstrument函数是否被管理:

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

play(100, sequenceInstruments);

You can see this in action on the Ramda REPL . 您可以在Ramda REPL上看到这一点。

I agree with @ftor: filter will allow you to compose in a more linear fashion, which leads to totally readable point-free code. 我同意@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);

This is assuming playInstruments is curried already. 假设playInstruments已经被管理。

With lodash/fp 's shorthands you could even do this: 使用lodash/fp的速记,您甚至可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM