[英]Functional way to execute a sub-array with Ramda
是否有可能使用Ramda進行以下操作時更具功能性的方式?
var time = 100;
sequenceInstruments.forEach(function(instrument){
if(instrument.on)
{
playInstrument(time, instrument.duration);
}
})
通過僅以無點方式使用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)
雖然我與斯科特克里斯托弗同意點FUL的解決方案是很容易,任何自由點的版本,你很可能會拿出,如果你有興趣開發一個免費的點對點版本了解,如果你想time
作為最終功能的參數, useWith
提供了可能useWith
的功能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上看到這一點。
我同意@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))
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.