2017-05-29 5 views
1

はのは、私は2つのbacon.jsの流れがあるとしましょうストリーム:私は変数に入力された長さでのフィルタリングの一般的なステップを抽出し、両方に適用したいリファクタリング共通コンビネータ

const stream1 = $('#input1').asEventStream('input') 
    .map(e => e.target.value) 
    .filter(inp => inp.length > 3) 
    .log(); 
const stream2 = $('#input2').asEventStream('input') 
    .map(e => e.target.value) 
    .filter(inp => inp.length > 3) 
    .log(); 

を後でストリームの、ファンタジーコード:

const my_filter = Bacon.map(e => e.target.value).filter(inp => inp.length > 3) 
const stream1 = $('#input1').asEventStream('input') 
    .apply(my_filter) 
    .log(); 
const stream2 = $('#input2').asEventStream('input') 
    .apply(my_filter) 
    .log(); 

それをするために慣用方法はありますか?

EDIT1:明確にするため、my_filterは例です。私はコンビネータの任意のチェーンをリファクタリングして複数のストリームに適用したいと考えています。

EDIT2:Bless Yahuが気付いたように、私はイベントからの価値を得るために追加の地図が必要です。これは私の問題をよりよく実証します。

答えて

1

これは基本的なソフトウェアリファクタリングの問題のようです。

通常、ストリームに任意の変換を適用する場合は、ストリームを引数としてとり、変更されたストリームを結果として返す関数を記述することをお勧めします。

具体的には、ステップを関数に抽出して重複を削除します。

const getValue = input => input.target.value 
const my_filter = stream => stream.filter(text => text.length > 3) 
const filteredInputValue = ($input) => { 
    my_filter($input.asEventStream('input').map(getValue)) 
const stream1 = filteredInputValue($('#input1')).log() 
const stream2 = filteredInputValue($('#input2')).log() 

この例では、調整やテキストトリミングなどの他の変換も適用できるように、my_filterを簡単に変更できます。

+1

あなたは創作者自身よりも上手くいくことはできません。 :)この回答は私にも役立ちます。 –

0

あなたが関数にmy_filter、そしてあなたのストリームにフィルタとそれを呼び出す変更、(私はベーコンのconvience機能はそこにもあると思います)イベントのうちの値を取得するためにマッピング機能を追加します。

const getValue = inp=>inp.target.value; 
const my_filter = inp => inp.length > 3 
const stream1 = $('#input1').asEventStream('input') 
    .map(getValue) 
    .filter(my_filter) 
    .log(); 
const stream2 = $('#input2').asEventStream('input') 
    .map(getValue) 
    .filter(my_filter) 
    .log(); 

この例はここにあります:http://jsbin.com/vahejuv/edit?html,js,console,output

関連する問題