Improving a lengthy TypeScript function through refactoring

Currently, I have this function that I am refactoring with the goal of making it more concise. For instance, by using a generic function.


setSelectedSearchOptions(optionLabel: string) {
    //this.filterSection.reset();
    this.selectedOption = optionLabel;
    this.selectedSearch = optionLabel;

    if (optionLabel === 'Registratie') {
       this.setFilterOptions(true, false, false, false, undefined, '', false, false, false, false);
    }

    if (optionLabel === 'Vcheq') {
        this.setFilterOptions(true, false, false, false, undefined, true, false, true, false, false);

    }

    if (optionLabel === 'Doelen') {
        this.setFilterOptions(true, false, false, false, undefined, ',', ',', ',', true, false);
    }
}

// Function to set filter options based on input
setFilterOptions(showDateOne: boolean, showDateTwo: boolean, showDateThree: boolean,
                  buttonFilterDisabled: boolean, startDateValue: any, 
                  isButtonVisible: any, showVcheqCode: boolean, showIndicator: boolean,
                  showMeasurement: boolean, showChallenge: boolean) {
    this.showDatePickerOne = showDateOne;
    this.showDatePickerTwo = showDateTwo;
    this.showDatePickerThree = showDateThree;
    this.buttonFilterDisabled = buttonFilterDisabled;
    this.startDate = startDateValue;
    this.isButtonVisible = isButtonVisible;
    this.showDropdownVcheqCode = showVcheqCode;
    this.showDropdownIndicator = showIndicator;
    this.showDropdownMeasurement = showMeasurement;
    this.showDropdownChallenge = showChallenge;
}

Although, I believe there might be a way to further shorten this function. Any ideas on how to achieve that?

Thank you

Answer №1

If you want to organize the values neatly, consider using a "table" structure like this:

const LABELS = ['Registration', 'Verification', 'Goals'];

const OPTIONS = {
                             // Registration   Verification   Goals
    showDatePickerOne:    [             1,           1,         1],
    showDatePickerTwo:    [             0,           1,         0],
    showDatePickerThree:  [             1,           1,         0],
    ...etc

};

Then, update your code with the following:

let index = LABELS.indexOf(optionLabel);

for (let [key, value] of Object.entries(OPTIONS)) {
    this[key] = value[index];
}

This method allows you to maintain concise code while retaining flexibility.

Answer №2

My approach would be something along these lines:

  setChosenOptions(selectedOptionLabel: string) {
    this.selectedOption = selectedOptionLabel;
    this.selectedSearch = selectedOptionLabel;

    switch (selectedOptionLabel) {
      case 'Registration':
        this.registration();
        break;
      case 'Vcheq':
        this.vcheq();
        break;
      case 'Goals':
        this.goals();
        break;
    }
  }

  private registration() {
    this.showDateSelectorOne = true;
    this.showDateSelectorTwo = false;
    this.showDateSelectorThree = false;
    this.filterButtonDisabled = false;
    this.startDate = undefined;
    this.selectedValue = '';
    this.showChallengeDropdown = false;
    this.showVcheqCodeDropdown = false;
    this.showMeasurementDropdown = false;
    this.showIndicatorDropdown = false;
  }

  private vcheq() {
    this.showDateSelectorOne = true;
    this.showDateSelectorTwo = false;
    this.showDateSelectorThree = false;
    this.showMeasurementDropdown = false;
    this.isButtonVisible = true;
    this.startDate = undefined;
    this.showVcheqCodeDropdown = true;
    this.showChallengeDropdown = false;
    this.showQrCodeDropdown = false;
    this.showIndicatorDropdown = false;
  }

  private goals() {
    this.showDateSelectorOne = true;
    this.showDateSelectorTwo = false;
    this.showDateSelectorThree = false;
    this.showMeasurementDropdown = false;
    this.isButtonVisible = false;
    this.startDate = undefined;
    this.selectedValue = ',';
    this.selectedOption = ',';
    this.selectedProgress = ',';
    this.showQrCodeDropdown = true;
    this.showChallengeDropdown = false;
    this.showVcheqCodeDropdown = false;
    this.showIndicatorDropdown = false;
  }

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

A Step-by-Step Guide to Launching PDF Blob from AJAX Response in a Fresh Chrome Tab

I'm sending a POST request to a server, and in response, I receive a PDF file that is returned as a blob. To handle this blob, I am using the "handle-as='blob'" attribute of iron-ajax (a Polymer element), just to cover all bases. Now, my g ...

When trying to use the exported Ionic 3 class in TypeScript, the error "Cannot find name 'ClassName'" occurs

When working on my Ionic 3 Application, I encountered an error stating "Cannot find name" when trying to use certain plugins. I initially imported the plugin like this: import { AndroidPermissions } from '@ionic-native/android-permissions'; and ...

How can I set up a KeyboardEvent listener in JavaScript?

My attempt to use @keydown resulted in an error: Type 'Event | KeyboardEvent' is not assignable to type 'KeyboardEvent'. Type 'Event' is missing the following properties from type 'KeyboardEvent': altKey, c ...

Link the selector and assign it with its specific value

Greetings, I am a newcomer to React Native and I am currently using Native Base to develop a mobile application. I am in the process of creating a reservation page where I need to implement two Picker components displaying the current day and the next one ...

Having trouble getting my Angular project up and running - facing issues with dependency tree resolution (ERESOLVE)

Currently, I am in the process of following an Angular tutorial and I wanted to run a project created by the instructor. To achieve this, I referred to the steps outlined in the 'how-to-use' file: How to use Begin by running "npm install" within ...

How can I write an if-else statement in JavaScript with Mongoose for MongoDB?

I am facing a challenge where I need to execute a statement only if the object is not null. If the object is null, I should skip executing anything. Is there a correct way to achieve this? I attempted it on MongoDB Playground but unfortunately, it did not ...

Hacking through external script injections into the browser

Curious about how certain software or programs are able to inject html,css,js into a web browser without the need for installing any extensions. Every time I open Chrome or Firefox, I'm bombarded with ads on popular sites like Google homepage, Faceboo ...

Include an Open OnClick event in the React/JSX script

We have a dynamic menu created using JavaScript (React/JSX) that opens on hover due to styling. My inquiries are: Instead of relying on CSS for the hover effect, where in the code can I implement an OnClick event to trigger the menu opening using Java ...

Webstorm seems to be having trouble identifying Next.js

When I create a Next.js app using the command npx create-next-app my-app --use-npm Everything is successfully installed, but when using WebStorm, I noticed that it does not auto import the <Link> component from Next.js. I have to manually import it ...

Converting a Curl command to a JavaScript POST request: best practices

Is it possible to convert the given curl code into a JavaScript post request that will function effectively in all browsers? curl https://connect.stripe.com/oauth/token \ -d client_secret=sk_test_f7PKXx5NRBFG5r41nTrPT7qB \ -d code="{AUTHORIZATIO ...

Exploring the functionalities of Angular components

I have encountered an issue while testing my class that relies on a single dependency, which is a service. Despite trying various methods such as using stubs, I am still facing the problem of an undefined method. https://i.stack.imgur.com/A3by2.png Testin ...

The front end button stubbornly refuses to comply and redirect to another page

I am having trouble getting my button element to redirect my page to another page. I have tried using an onclick function inside the button tag with window.location.href, as well as creating a separate function for the redirect, but nothing seems to be wor ...

HTML various button designs - such as a cogwheel

I need a button on my Angular/Electron project that resembles a gear icon. I came across these resources: here and here. However, when I tried to implement them, they didn't work as expected. Currently, the button looks like this: <button class= ...

Anticipating the completion of multiple observable subscription functions

Is there a way to replace and convert all words in an array using an object's method that returns an observable? I found a helpful solution on this post which uses bind to pass the correct value. After all subscriptions are complete, I want to execut ...

Why won't JavaScript functions within the same file recognize each other?

So I have multiple functions defined in scriptA.js: exports.performAction = async (a, b, c) => { return Promise.all(a.map(item => performAnotherAction(item, b, c) ) ) } exports.performAnotherAction = async (item, b, c) => { console.log(`$ ...

How can a custom event bus from a separate account be incorporated into an event rule located in a different account within the CDK framework?

In account A, I have set up an event rule. In account B, I have a custom event bus that needs to act as the target for the event rule in account A. I found a helpful guide on Stack Overflow, but it was specific to CloudFormation. I am providing another a ...

What is the process for identifying children records of a parent (Adonis Lucid Many-to-Many) that match a specific criteria?

I am currently searching for the presence of specific Permissions within a single parent Role in a many-to-many relationship. const roles = await Role .query() .preload('permissions') this.role = roles.find(role => role.id === someid) co ...

Displaying Angular Material slider with minimum and maximum labels visible

I'm currently working with the Angular Material slider and I want to have labels at both ends of the slider indicating the minimum and maximum values. Additionally, I would like to incorporate a scale with points and corresponding labels to show the r ...

Choosing the most suitable stylesheet in Angular 8 when multiple CSS files are present

In my project, I have several CSS stylesheets for angular components. I am curious if there is a method to designate a preferred stylesheet when multiple sheets loaded by a component contain the same styles but with different values. ...

HTML, JavaScript, and PHP elements combine to create interactive radio buttons that trigger the appearance and disappearance of mod

On my page, I have multiple foreach loops generating divs with different information. These divs are displayed in modals using Bootstrap. However, I am encountering an issue where if I select a radio button and then close the modal and open another one, th ...