Tips for Simplifying Complex Switch Cases with Object Literals in TypeScript

I have a unique situation where I need to switch between two functions within an object literal. One function takes two numerical arguments, "A" and "B", while the other function only takes a single string argument, "C".

My TypeScript code showcases my dilemma:

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 options = {
      0: this.firstFn.apply(this, [1, 1]),
      1: this.secondFn.apply(this, ['k']),
    };

    this.result = options[this.v];

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

In my HTML code, I utilize a button trigger to execute the 'doStuff()' function.

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

{{ result }}

If you want to take a look at my implementation on StackBlitz, check it out here: https://stackblitz.com/edit/angular-9-starter-kq1nrx

An issue I currently face is that both the functions inside the object are being executed when I call 'doStuff()', instead of just the selected one. You can observe this in the stackblitz console.

Do you have any suggestions on how I can prevent this double function call?

Answer №1

The best solution is to swap out .apply() for .bind(). By using bind, the function is not immediately called, preventing the output of two logs.

Furthermore, remember that you must now call the function when obtaining the reference:

this.result = opt[this.v]();

Here's the revised code:


  doSomething() {
    const options = {
      0: this.firstAction.bind(this, [1, 1]),
      1: this.secondAction.bind(this, ['k']),
    };

    this.result = options[this.v]();

    //Switch between the two actions
    this.v === 1 ? this.v-- : this.v++;
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Typescript is failing to return nested types when attempting to return a nested object

My goal is for my function to return a nested type of Content, but it's not working even though the type that should be returned is known. Let's take a look at an example: type Content = { some: { extra: string; prop: number; ...

JavaScript: Retrieve the Number of Subscribers on the BroadcastChannel

Is there a way to check if a Broadcast channel exists and see how many subscribers it has? We have a product link, and some Chrome tabs are subscribed to a Broadcast channel. We want to determine the number of listeners. const bc = new window.BroadcastCha ...

Having trouble resolving all parameters for the service in an Angular2 test with Jasmine mocking

I am currently attempting to create a mock service for testing purposes: Production: @Injectable() export class UserService extends DtoService { // irrelevant details here. } @Injectable() export abstract class DtoService { constructor(private h ...

Having trouble implementing a CSS style for a Kendo-checkbox within a Kendo-treeview component

I am facing a The issue I am encountering is that while the CSS for k-treeview is being applied from the scss file, it is not being applied for the kendo-checkbox I attempted to resolve the problem by using the following code: <kendo-treeview ...

Choose a value, then multiply it by a number using a reactive

I have been attempting to multiply a fixed value by the selected value of a mat-select element, for example A x B, where A remains constant and does not change while B is the changing value from the mat-select. After performing this multiplication, I aim ...

Can you use the useCallback function within a nested callback function?

within component A: const retrieveOnClick = useCallback( (rec: GenericRec): (() => void) => () => { setSelectedRecord(rec); }, [], ); inside component B which is a child of A: const displayRecord = useCallback( (row: Row& ...

Issue with Service Workers functionality in Angular 8 has been identified

Issue http://localhost:8080/ Requests that are not handled will be directed to: http://localhost:8080 Press CTRL-C to stop the server [2019-06-21T06:37:57.110Z] "GET /" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Geck ...

Is it feasible to access and modify local files within an Angular project using TypeScript code in the angular component.ts file? If so, how can this be achieved?

My Angular application is built on version 4 or higher. I have a setup in my project where there is a folder containing a txt file and another folder next to it with an angular component.ts file: FolderWithFile -----file.txt ComponentFolder -----person.co ...

Error message encountered in Next.js when trying to import 'SWRConfig' from 'swr': ClerkProvider Error. The import is not successful as 'SWRConfig' is not exported from 'swr

I recently started working on a new Next.js project and integrated Clerk into it. I set up the env.local and middleware.ts files before wrapping the HTML div with ClerkProvider. However, when attempting to run the project locally, I encountered the followi ...

Encountering issue while resolving flux/utils in webpack

My TypeScript OS project is in the process of being migrated to webpack, Unfortunately, I am currently facing a build error: ERROR in ./src/store/GigaStore.ts Module not found: Error: Cannot resolve module 'flux/utils' in /home/erfangc/GigaGrid ...

Tips on using the `IsEqual` function to develop a tool that verifies the similarity of different data types

When working with TypeScript, I often utilize the type-fest npm package in my coding. For documentation purposes, I sometimes like to assert that two types are either equal or unequal. Here is an example: const b: IsEqual<{a: 1}, {a: 1}> = true; con ...

How can I reduce unnecessary spacing in a primeNg Dropdown (p-dropdown) filter within an Angular 5 application?

In my Angular 5 project, I have implemented PrimeNG dropdown (p-dropdown) and encountered an issue. When I try to filter the dropdown data by adding spaces before and after the search term, it displays a No Results Found message. How can I fix this problem ...

What causes the error "property does not exist on type" when using object destructuring?

Why am I encountering an error in TypeScript when using Object destructuring? The JavaScript code executes without any issues, but TypeScript is showing errors. fn error: This expression is not callable. Not all elements of type '(() => void) | ...

Deactivate input fields in FormArray using a checkbox

I am currently working on a multi-step form that includes a FormArray for schools in the third step. Within this FormArray, there is an input field called 'endDate' where users can check a checkbox labeled 'En Curso' (in progress) if th ...

What is the best way to send an email with a time-sensitive code (token) using Firebase?

Currently, I am developing an application that requires sending a verification code to users before they can proceed with certain actions. For instance, when users log in to the app, they need to enter their email, password (authenticated using Firebase au ...

Exploring the zorro components (nz-tree) in Angular for effective testing with Jasmine and Karma

How can I access the data in the $event and verify if the treeClick method is being called upon click? When running the test file, I encountered the following error: "Expected spy treeClick to have been called once. It was called 0 times." In t ...

The property 'x' is not found on 'Reel' type in this context

Creating a custom class extending Container in PIXI.js: export class CustomContainer extends Container { constructor(width: number, height: number) { super(); var sprite: Sprite = Sprite.fromImage("assets/images/elephant.png"); ...

Angular 5: experiencing issues with HttpClient when using REST API

Currently, I am in the process of developing a REST API using Spring to perform CRUD operations based on a tutorial I found. However, I have encountered an issue with the HTTP client not retrieving data, and upon inspection, I discovered the following erro ...

Extending a class with diverse types in Typescript: A guide

I have a class with multiple methods that deal with an entity referred to as "entity." class entity { entityName: string = ''; getList(): any[] { someAPI + this.entityName .... } getOne(): any{ } } Additionally, there are specifi ...

What are some ways I can enhance the typography within Material UI?

Currently, I am in the process of developing a custom theme utilizing createMuiTheme. However, my application requires more typography variants than what Material UI provides out of the box. I need to extend the typography so that it aligns with my specifi ...