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

What are some techniques for concealing a CSS transition beneath another element in both directions?

Witness the magic in action! By clicking on the black box below, a larger black box will gracefully emerge from beneath the sidebar. While it may not be as clear in jsfiddle, rest assured that this effect is more pronounced in browsers. Thanks to some clev ...

Issue updating @angular/core in Angular CLI caused by rxjs dependency

Currently, I am in the process of updating angular and angular material to version 6. I have successfully updated the cli to allow for the new ng update command. However, when attempting to use it to update @angular/core, I encounter an error stating that ...

Error: It seems like Material UI has updated their export structure and now `makeStyles` is no longer available in the

The export of makeStyles from @mui/material/styles has been deprecated. Despite importing from @mui/styles throughout my project, this error continues to appear. I have already tried removing the node_modules folder and reinstalled, but the issue persis ...

"Can you explain the functioning of this Node.js middleware when it doesn't require any

Currently, I am utilizing a function created by another individual for express and passport, which defines the middleware in the following manner: function isLoggedIn(req, res, next) { if (req.isAuthenticated()){ return next(); } els ...

Error management and callback handling in MSAL.js for Angular 6 Single Page Applications

I am currently using msal.js in an angular 6 SPA for authentication purposes, but I have encountered a few issues: Initially, I struggled to find clear examples on how to handle errors with the library, so I pieced together information from various source ...

Accessing a property's value from a different property within a Class' initialization function

I encountered a challenge while trying to access the value returned in one method within a property of another method belonging to a different constructor. The specific error message I received was "TypeError: Cannot read property 'name' of undef ...

When debugging in Visual Studio 2013, Typescript variables/fields consistently show up as undefined

What is the reason behind the properties/field variables in Typescript being consistently undefined during debugging in Visual Studio 2013? ...

Twice the data fetching through ajax on popup is observed using php mysql

I've been struggling for the past two hours. Attempted : location.reload(); reset form Tried many features, but after closing my popup and reopening it or opening another ID, the previous ID data is still visible. This happens continuously for all ...

Eliminate jQuery's delayed blinking effect with the use of an event

Utilizing the mouseenter and mouseleave events, I have implemented a functionality to add a button (not actually a button) to an <li>. However, there seems to be a problem with my code. The button appears and disappears on mouseleave and mouseenter, ...

jQuery form validation with delay in error prompts

I am experiencing a strange issue with my HTML form validation function. It seems to be showing the alert div twice, and I can't figure out why this is happening. Adjusting the delay time seems to affect which field triggers the problem. Can anyone sp ...

Vue.js axios method returns undefined; v-for directive fails to iterate - Issue on Wordpress site

Using a shortcode, I have integrated Vue.js into a Wordpress page. pl2010_vue_init_directory = pl2010_vue_init_directory || (function(ctx) { new Vue( { el: '#'+ctx.el, data: { errorMsg: "", successMsg: "", show ...

Changing the width of the file input using css

Clicking just below the word demonstration also triggers a click on the input type file. How can this be avoided so that the click event only fires in the intended area regardless of size? <!DOCTYPE html> <html> <body> <style> in ...

Implementing fetch within a custom hook to display a loader within a return function

customFetch hook: import React, { useState, useEffect } from 'react'; const customFetch = (url, options) => { const [response, setResponse] = useState(null); const [error, setError] = useState(null); useEffect(() => { (async () ...

What is causing the issue with using transition(myComponent) in this React 18 application?

Recently, I have been immersed in developing a Single Page Application using the latest version of React 18 and integrating it with The Movie Database (TMDB) API. My current focus is on enhancing user experience by incorporating smooth transitions between ...

Should scripts be replayed and styles be refreshed after every route change in single page applications (SPA's)? (Vue / React / Angular)

In the process of creating a scripts and styles manager for a WordPress-based single page application, I initially believed that simply loading missing scripts on each route change would suffice. However, I now understand that certain scripts need to be ex ...

Ways to link a Javascript or Jquery function to an HTML form

I am looking to develop a form that can extract email addresses from input text. While I know there are many scripts available that can do this quite easily, my goal is to create one on my own. After reading, researching, and experimenting with differ ...

Having trouble with your AngularJS ng-repeat functionality?

As a newcomer to AngularJs, I am still grappling with the basics. Currently, I am using the Soundcloud API to retrieve a list of followers for a specific user. In my $scope.init function, I have managed to establish a connection with Soundcloud, authentica ...

Dialogue box closes automatically within a dropdown menu

I am using shadcn in my next.js 13 project and I want to implement a dropdown feature that allows users to edit or delete an entry. However, when the user clicks on "delete", the dialog pops up for only about 0.5 seconds before closing along with the dropd ...

What steps can be taken to avoid being logged out automatically upon clicking the back button?

Currently, my code automatically logs out of the application when the browser is closed. However, I am facing an issue where it also logs out when I press the browser's back button and navigate to another page. I would like the code to only logout au ...

validation using ajax and php

One question I have is, when I include document.getElementById('myPassword').value); in the validarDados function, it corresponds to valor. Then I need another variable, but valor1 isn't working as expected. The result of echoing $valor1; is ...