JavaScript函数组成3个函数 [英] JavaScript function composition from 3 functions

查看:82
本文介绍了JavaScript函数组成3个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Vue并尝试使用JS函数组合过滤结果数组。

I'm using Vue and trying to filter an array of results using a JS function composition.

我的Vue计算值是这样的,但无法获得 filteredByAll 接受第三个选项 getByThing 。现在filterByAll只过滤类别和关键字搜索。

My Vue computed values are like so, but can't get filteredByAll to accept a third option getByThing. Right now the filterByAll just filters on the category and keyword search.

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)
}

我正试图包裹我的脑袋围绕功能性的东西,但从我读过的东西中挣扎。

I'm trying to wrap my head around the functional stuff but struggling from what I've read.

推荐答案

这应该这样做:

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

这篇关于JavaScript函数组成3个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆