DEV Community

Cover image for Conditional Statements: Part 2
Rahul Raj
Rahul Raj

Posted on

Conditional Statements: Part 2

The issue with legacy conditional statements.

The main issue is, it is ugly and boring. See the Part 1.

It takes a lot of time to write conditions and maintain them consider the below.

  private demo(myVar: string): string {
    if(myVar === 'condition') {
      return myVar.substring(1,3);
    }
    if(myVar === 'demo') {
      return myVar.substring(1,2);
    }
    if(myVar === 'thing') {
      return myVar.substring(1,4);
    }
    if(myVar === 'demo1') {
      return myVar.substring(1,5);
    }
    if(myVar === 'demo5') {
      return myVar.substring(1,2);
    }
    return '';
  }
Enter fullscreen mode Exit fullscreen mode

Now the above code can be good in some case but we can do better.
USING OBJECT FOR CONDITIONING

  private demo1(myVar: string): string {
    const myObject: { [key: string]: string; } = {
      'condition': myVar.substring(1,3),
      'demo': myVar.substring(1,2),
      'thing': myVar.substring(1,4),
      'demo1': myVar.substring(1,5),
      'demo5': myVar.substring(1,2),
    }
    return myObject[myVar];
  }

  demo1('condition'); 
Enter fullscreen mode Exit fullscreen mode

It will work same as the above if statements but it is a clean code.

Want to check the default condition as well?

  private demo1(myVar: string): string {
    const myObject: { [key: string]: string; } = {
      'condition': myVar.substring(1,3),
      'demo': myVar.substring(1,2),
      'thing': myVar.substring(1,4),
      'demo1': myVar.substring(1,5),
      'demo5': myVar.substring(1,2),
      default: '',
    }

    if(!myObject[myVar]) return myObject['default'];
    return myObject[myVar];
  }
Enter fullscreen mode Exit fullscreen mode

This reduces the overall cognitive complexity as well.

With this we can even have function calls.

  public coc(troopName: string, quantity: number): string {
    const bookForCOC: { [key: string]: any } = {
      'barbarian': () => quantity > 30 ? 'Use it behind kind' : 'Use it to destroy',
      'archer': () => quantity > 20 ? 'Use it behind queen' : 'Use it to destroy',
      'balloon': () => quantity > 20 ? 'Use it behind dragons' : 'Use it after air defense is destroyed',
      'dragon': () => quantity > 3 ? 'Use it at a single place' : 'Use it anywhere else',
      default: () => 'Use some good troops to win'
    }

    if(!bookForCOC[troopName]) return bookForCOC['default']();
    return bookForCOC[troopName]();
  }
Enter fullscreen mode Exit fullscreen mode

This can be used as an alternative for conditional statements

If you like the post follow me for more

Top comments (0)