0👍
Something like this would work. not sure about the logic though (only take the syntax change)
this.filteredOut = (!cupFilters.intensities.length || !cupFilters.moments.length)
? false
: (!cupFilters.intensities.includes(this.cup.intensity) || !cupFilters.moments.includes(this.cup. coffee_moment_id)) ;
0👍
you’re not taking into account any of your previous results. The boolean operations help here.
Let’s start with what you’re currently doing:
let toFilter;
if (a) {
toFilter = false;
return;
}
toFilter = b;
toFilter = c;
Let’s say a = false, b = true, c = false
, I assume you’d want toFilter
to be true
, as one of the conditions is true. What happens instead is that we see that toFilter
is false
.
To understand why, you can see that the code won’t return, as the first condition is false
and the if
won’t run. Then toFilter
is set to true
as the second condition is true
, but then the previous value of toFilter
is disregarded, and it’s set to false
.
To avoid this, one possibility is to make all the code look like the first case:
let toFilter;
if (a) {
toFilter = false;
return;
}
if (b) {
toFilter = true;
return;
}
if (c) {
toFilter = true;
return;
}
Now, there’s clearly some duplicate code, but it will work.
We can use boolean operators to shorten it:
const toFilter = !a && (b || c);
It’s important to note that boolean operators shortcircuit. For x && y
this means that if x
is false
, then y
won’t even be evaluated. For x || y
, if x
is true
, then y
won’t be evaluated, which means you aren’t going to get errors or extra computations.
For you,
toFilter = this.filteredOut;
a = !cupFilters.intensities.length || !cupFilters.moments.length;
b = !cupFilters.intensities.includes(this.cup.intensity);
c = !cupFilters.moments.includes(this.cup. coffee_moment_id);
Noting that !(!x || !y)
is the same as x && y
, and !x || !y
is the same as !(x && y)
, your code can comfortably be
const { intensities, moments } = cupFilters;
this.filteredOut = (intensities.length && moments.length)
&& !(intensities.includes(this.cup.intensity) && moments.includes(this.cup.coffee_moment_id));
Feel free to rewrite this in whatever layout makes it more readable for you