way to always call a function without repeating code inside a function with guard clauses

201 views Asked by At

I have a function which looks like this:

function myFunc(){
  if (!condition1){
    //some extra code (diff. from condition2 if-statement)
    doSomething();
    return;
  }
  if (!condition2){
    //some extra code (diff. from condition1 if-statement)
    doSomething();
    return;
  }
  //some extra code (diff. from both condition if-statement)
  doSomething();
}

I would like to know if there is a way to simplify this code so the function doSomething() always execute (like in Java with try/catch/finally).

1

There are 1 answers

0
NewbieInFlask On BEST ANSWER

Using try/catch[optional]/finally solved my problem.

try {
  (function myFunc(){
    if (!condition1){
      //some extra code (diff. from condition2 if-statement)
      return;
    }
    if (!condition2){
      //some extra code (diff. from condition1 if-statement)
      return;
    }
    //some extra code (diff. from both condition if-statement)
  })();
} finally {
  doSomething();
}