'How to use object literals in TS to replace complex switch cases?

I have the following scenario: In a switch, I call two different functions based on the case. The first function has args "A" and "B" which are numbers and the second function has an arg "C" which is a string.

Now I am wondering if it is possible to convert this switch statement into an object literal.

My TS code:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular';
  result: string = null;
  v: number = 1;

  firstFn(a: number, b: number) {
    console.log(1);
    if (a == undefined && b == undefined) return 'missingParam';
    return a == b ? 'Equal' : 'Not';
  }

  secondFn(c: string) {
    console.log(2);
    return c ? c : 'noParam';
  }

  doStuff() {
    const opt = {
      0: this.firstFn.apply(this, [1, 1]),
      1: this.secondFn.apply(this, ['k']),
    };

    this.result = opt[this.v];

    //Toggle between the two functions
    this.v == 1 ? this.v-- : this.v++;
  }
}

My HTML code:

<button (click)="doStuff()">Do stuff</button>

{{ result }}

Here is my attempt in stackblitz: https://stackblitz.com/edit/angular-9-starter-kq1nrx

The problem that I am facing is that now when I call the "doStuff()" function both functions attached to the properties of the object are calculated instead of just the one that is selected. (You can check that by checking the console in stackblitz)

Is there a way to avoid this double function call? If yes how?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source