Avoid a lot of conditions inside an If Statement

60 views Asked by At

I have an if statement like this

if(areEqual(a,ax) && areEqual(b,bx) && areEqual(c,cx) && areEqual(d,dx) && areEqual(e,ex) && areEqual(f,fx) && areEqual(g,gx) && areEqual(h,hx) && areEqual(i,ix) && areEqual(j,jx) && areEqual(k,kx)

This if the statement includes lots of conditions and it is not readable. How can I avoid this situation? Is there any pipeline pattern for if conditions?

2

There are 2 answers

1
Krishna On

Assuming you are using Python, you can store all check in a list(say list1) and check

if sum(list1)==len(list1):
  do something
1
SollyBunny On

In javascript, if you add true and true together you get 2. Using this information you could put all the conditions in an array and get the sum of it.

var conditions = [condition1, condition2, ... ]; -- all conditions go here

var sum = 0; -- works out the sum
for (var i = 0; i < conditions.length; i++) {
    sum += conditions[i];
}

if (sum === conditions.length) {
    console.log("success")
}