使用ES6改进过滤逻辑

时间:2019-01-19 12:53:46

标签: javascript

在我的VueJS应用程序中,我具有计算属性,该属性可以与ES6函数相关,并且此函数的目的是过滤变量this.classes。撇开变量的内容,我觉得我的解决方案有点“笨拙”,我想知道是否还有另一个我不熟悉的ES6功能可以帮助我改善这种逻辑并使它更容易理解? >

此处是当前功能

filteredClasses() {
      let hasGrades = this.gradeFilter.length;
      let haSubjects = this.subjectFilter.length;

      if (!hasGrades && !haSubjects) return _.flatMap(this.classes); // return all if no filter

      return _.flatMap(this.classes).filter(x => {
        return (
          x.name === this.selectedClass.name ||
          (this.gradeFilter.map(el => el.value).includes(x.grade) &&
            !haSubjects) ||
          (this.subjectFilter.map(el => el.value).includes(x.subjectId) &&
            !hasGrades) ||
          (this.gradeFilter.map(el => el.value).includes(x.grade) &&
            this.subjectFilter.map(el => el.value).includes(x.subjectId))
        );
      });
    }
  }

2 个答案:

答案 0 :(得分:2)

与ES6无关,但您应该简化条件

(A && ¬Y) || (B && ¬X) || (A && B && X && Y)

公正

(A || ¬X) && (B || ¬Y)

我还建议使用some而不是map + includes。这两项更改将使您的代码更易于阅读,并且效率更高:

filteredClasses() {
  const {gradeFilter, subjectFilter} = this;
  return _.flatMap(this.classes).filter(x =>
    x.name === this.selectedClass.name
    || (!gradeFilter.length || gradeFilter.some(el => el.value === x.grade))
    && (!subjectFilter.length || subjectFilter.some(el => el.value === x.subjectId))
  );
}

答案 1 :(得分:0)

可以通过避免在.map()的每次迭代中执行相同的.filter()来提高效率:为其创建一个Set,然后使用.has()检查成员资格:

filteredClasses() {
    const hasGrades = this.gradeFilter.length;
    const hasSubjects = this.subjectFilter.length;
    const gradeSet = new Set(this.gradeFilter.map(el => el.value));
    const subjectSet = new Set(this.subjectFilter.map(el => el.value));

    return _.flatMap(this.classes).filter(x => 
        x.name === this.selectedClass.name ||
        (  (!hasGrades || gradeSet.has(x.grade)) && 
           (!hasSubjects || subjectSet.has(x.subjectId))  )
    );
}