2017-01-11 26 views
0

私はVueを使用しており、JS関数の構成を使用して結果の配列をフィルタリングしようとしています。3つの関数からのJavaScript関数の構成

My Vueの計算値はそうですが、filteredByAllには3番目のオプションgetByThingを受け入れることができません。現在、filterByAllはカテゴリーとキーワード検索だけをフィルタリングします。

computed: { 
     filteredByAll() { 
     return getByCategory(getByKeyword(this.list, this.keyword), this.category) 
     }, 
     filteredByKeyword() { 
      return getByKeyword(this.list, this.keyword) 
     }, 
     filteredByCategory() { 
      return getByCategory(this.list, this.category) 
     }, 
     filteredByThing() { 
     return getByThing(this.list, this.thing) 
     } 
    } 

マイ標準JS機能

function getByKeyword(list, keyword) { 
    const search = keyword.trim() 
    if (!search.length) return list 
    return list.filter(item => item.name.indexOf(search) > -1) 
} 

function getByCategory(list, category) { 
    if (!category) return list 
    return list.filter(item => item.category === category) 
} 

function getByThing(list, thing) { 
    if (!thing) return list 
    return list.filter(item => item.thing === thing) 
} 

は、私は、機能のものの周りに私の頭をラップしようとしているが、私は何を読んでから苦労しています。

答えて

2

これはそれを行う必要があります。

filteredByAll() { 
    return getByThing(getByCategory(getByKeyword(this.list, this.keyword), this.category), this.thing) 
}, 
+0

ああ、内から外に行くので右か? –

+0

はい、各関数はリストを返します。したがって、関数の結果をリストパラメータとして次の関数に単に差し込むことができます。順序は、結果の最も少ない数が何であれ、最初にフィルタリングすることによって速度を最適化できる限り、関連性があります。 –

+0

おかげさまでクリス - 私は思う*私はそれを取得し、前に間違っていた。私はそれを他の方法で試していたと思う。 –

1

我々はcurriedバージョンに機能を書き換え、最後の引数は、我々は彼らが好きcomposeできるリストのとき:

const trippleFilter = (keyword, category, thing) => pipe (
    getByKeyword (keyword), 
    getByCategory (category), 
    getByThing (thing) 
) 

ワーキングコード

const pipe = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))) 
 

 
const getByKeyword = keyword => list => { 
 
    const search = keyword.trim() 
 
    return !search.length 
 
     ? list 
 
     : list.filter(item => item.name.indexOf(search) > -1) 
 
} 
 
    
 
const getByCategory = category => list => 
 
    !category 
 
     ? list 
 
     : list.filter(item => item.category === category) 
 
    
 
const getByThing = thing => list => 
 
    !thing 
 
     ? list 
 
     : list.filter(item => item.thing === thing) 
 

 
const trippleFilter = (keyword, category, thing) => pipe (
 
    getByKeyword (keyword), 
 
    getByCategory (category), 
 
    getByThing (thing) 
 
) 
 

 
const x = [ 
 
    { 
 
     name: 'pizza', 
 
     category: 'fastfood', 
 
     thing: 'pizza salami' 
 
    }, 
 
    { 
 
     name: 'burger', 
 
     category: 'fastfood', 
 
     thing: 'hamburger' 
 
    } 
 
] 
 

 
console.log(trippleFilter ('pizza', 'fastfood', 'pizza salami') (x))

関連する問題