JavaScript函数组成3个函数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript函数组成3个函数相关的知识,希望对你有一定的参考价值。
我正在使用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)
}
我试图绕过功能性的东西,但是从我读过的东西中挣扎。
答案
这应该这样做:
filteredByAll() {
return getByThing(getByCategory(getByKeyword(this.list, this.keyword), this.category), this.thing)
},
另一答案
当我们将函数重写为curried版本并且最后一个参数是列表时,我们可以像compose一样:
const trippleFilter = (keyword, category, thing) => pipe (
getByKeyword (keyword),
getByCategory (category),
getByThing (thing)
)
Working Code
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))
以上是关于JavaScript函数组成3个函数的主要内容,如果未能解决你的问题,请参考以下文章