Home > Software engineering >  (JavaScript) Best was to check for multiple conditions and end execution as soon as one returns fals
(JavaScript) Best was to check for multiple conditions and end execution as soon as one returns fals

Time:05-14

I am currently working on a duty rota App. I need to calculate which employee can work on every particular day of the month. This must also be updated "on the fly" since if someone gets assigned to work on day 1, he/she for example can't work on day 2.

If someone can work on a day or not depends on multiple conditions. My Idea is, to have a "controller"-function which checks, if any of the "conditions"-functions returns false = that means, the person is not available for that day.

I fond a way by simply multiplying the return-values like

const controller = (day, employee) => {
  return (
   cond1(day, employee) * 
   cond2(day, employee) * 
   cond3(day, employee) * 
   cond4(day, employee) * 
   cond5(day, employee)
  )
}

since true == 1 and false == 0 it returns 0 as soon as one condition is false. But I thought this might not be the most efficient way because it checks for all conditions. I am looking for a way to return as soon as one condition is false.

I could use if-else but this would become unreadable condition-hell very fast

CodePudding user response:

&& will shortcircuit if the first value is false. Try this out:

function foo() {
  console.log('called foo');
  return false;
}
function bar() {
  console.log('called bar');
  return true;
}

foo() && bar()

The output should only be called foo. Shortcircuiting means that the boolean expression will only evaluate as much as it needs to; if the left side of the && is false, then the expression is false, and the right side doesn't need to be evaluated. Note that this also happens with ||, but in the opposite way: if the left side of the expression is true, the right side isn't evaluated.

If all the functions take the exact same arguments as your example implies, you could use [].every, which also "short circuits" by ending iteration early. I would caution against this for your specific example, though, as it can make things hard to maintain in the event that even one of those cond functions takes different parameters.

[cond1, cond2, cond3, cond4, cond5].every((cond) => cond(day, employee))
  • Related