ganesh kaspate
ganesh kaspate

Reputation: 2695

How to remove multiple if statements in javascripts

I have following piece of code.

  a = []
   b = []
   c = []
useEffect(() => {

if(isEmpty(a) && isEmpty(b) && isEmpty(c)) {
   data.refetch()
}
if(data.isFetching){
  //do something
}

if(response.isFetching){
  //do something
}

}, [ //Some depedencies ])

SO, is there any way through which I can modify this if statements. As I tried with the switch statements but it is not helping over here. So, Any suggestion would e great. Thanks.

Upvotes: 0

Views: 385

Answers (1)

Santiago Ivulich
Santiago Ivulich

Reputation: 352

You can remove every if of the code in the following way:

a = [];
b = [];
c = [];
conditions = [
[[a,b,c].every((x) => isEmpty(x)), () => data.refetch()],
[data.isFetching, someOtherFunction],
[response.isFetching, anotherFunction]
];
conditions.forEach(cond => cond[0] && cond[1]());

I would not recommend this as it makes your code less readable and confusing.

Explanation:

The function every will test condition for every element of an array and joining with an and:

...
 [a,b,c].every((x) => isEmpty(x)) 
...

Then to test every condition you can add them to an array and iterate through them, with a callback for every if you want to create:

conditions = [
[[a,b,c].every((x) => isEmpty(x)), () => data.refetch()],
[data.isFetching, someOtherFunction],
[response.isFetching, anotherFunction]
]
condtions.forEach((cond) => { if(cond[0]) cond[1]() } )

Then As suggested by derpirscher you could remove the last if with

conditions.forEach(cond => cond[0] && cond[1]());

But again, this makes your code more confusing, I would suggest keeping the ifs to make it more clear.

Upvotes: 3

Related Questions