Reputation: 15
So I m building one game which is drenching the field according to selected colour and I have 4 different conditions:
let condition1 = drenchX + 1 === mixedX && drenchY === mixedY && this.mixedFields[i].style.backgroundColor === this.service.clickedColor;
let condition2 = drenchX === mixedX && drenchY + 1 === mixedY && this.mixedFields[i].style.backgroundColor === this.service.clickedColor;
let condition3 = drenchX - 1 === mixedX && drenchY === mixedY && this.mixedFields[i].style.backgroundColor === this.service.clickedColor;
let condition4 = drenchX === mixedX && drenchY - 1 === mixedY && this.mixedFields[i].style.backgroundColor === this.service.clickedColor;
I need to get all possible combinations of this conditions, all 4 of them can be true, or 3 or 2 or just one. This works fine but I think it is too long. My if statement looks like this:
if((condition1 && condition2 && condition3 && condition4) || (condition1 && condition2 && condition3) || (condition1 && condition2 && condition4) || (condition1 && condition3 && condition4) || (condition2 && condition3 && condition4) || (condition1 && condition2) || (condition1 && condition3) || (condition1 && condition4) || (condition2 && condition3) || (condition2 && condition4) || (condition3 && condition4) || condition1 || condition2 || condition3 || condition4) {
// some action
}
It all works perfectly but I m looking for a shorter solution and I m still a beginner in this. So if anyone know a better way to do this that would be great, my statement is just too long and it doesn't looks good at all. Btw, project is in Angular. Maybe to create some function for this?
Upvotes: 0
Views: 68
Reputation: 15
Thanks everyone for advices, but I found a way to simplify it. I stored conditions into array and used for-in to loop thru all possible conditions.
let conditionalArray: boolean[] = [condition1, condition2, condition3, condition4];
for(let c in conditionalArray){
if(conditionalArray[c]) {
//....
}
}
Upvotes: 0
Reputation: 33
If I understand correctly, the if-statement is checking whether any of the conditions are met. Therefore, this should do the trick:
if(condition1 ||
condition2 ||
condition3 ||
condition4)
{
//some action
}
Upvotes: 0
Reputation: 338
If a && b
is true, then a || b
is also true. That said it means your condition can just be
if (condition1 || condition2 || condition3 || condition4)
Upvotes: 2