我正在使用Vue并尝试使用JS函数组合过滤结果数组。
我的Vue计算值是这样的,但不能filteredByAll
接受第三个选项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)
}
我试图绕过功能性的东西,但是从我读过的东西中挣扎。
答案 0 :(得分:2)
这应该这样做:
filteredByAll() {
return getByThing(getByCategory(getByKeyword(this.list, this.keyword), this.category), this.thing)
},
答案 1 :(得分:0)
当我们将函数重写为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))