Tips for preventing duplicate Java Script code within if statements

In my function, there are various statements to check the visibility of fields:

 isFieldVisible(node: any, field: DocumentField): boolean {
        if (field.tag === 'ADDR_KOMU') {
            let field = this.dfs_look(node.children, 'ADDR_APPLICANTTYPE');
            return field.fieldvalue == 1;
        }

        if (field.tag === 'ADDR_SNAME') {
            let field = this.dfs_look(node.children, 'ADDR_APPLICANTTYPE');
            return field.fieldvalue == 1;
        }

        if (field.tag === 'ADDR_FNAME') {
            let field = this.dfs_look(node.children, 'ADDR_APPLICANTTYPE');
              return field.fieldvalue == 1 || field.fieldvalue == 2;
        }
}

To enhance the function and prevent duplicates, consider using a more modular approach.

I experimented with using foreach loops with tuples for iteration but encountered difficulties in returning boolean values from them.

Answer №1

To prevent redundant code, you can utilize the JavaScript OR(||) operator within an if statement.

isFieldVisible(node: any, field: DocumentField): boolean {   
       if (field.tag=== 'ADDR_KOMU' || field.tag=== 'ADDR_SNAME' || field.tag=== 'ADDR_FNAME' ) {
          let field= this.dfs_look(node.children, 'ADDR_APPLICANTTYPE');            
          if(field.tag=== 'ADDR_FNAME'){
            return field.fieldvalue == 1 || field.fieldvalue == 2;
          }             
          return field.fieldvalue == 1;         
    }

}

For more information on how to use the logical "OR" operator (||) in javascript, refer to this resource.

Answer №2

Using a switch statement can effectively reduce redundancy in the code.

isFieldVisible(node: any, field: DocumentField): boolean {
        let selectedField;
        
        switch(field.tag) {
            case 'ADDR_KOMU':
            case 'ADDR_SNAME':
                selectedField = this.dfs_look(node.children, 'ADDR_APPLICANTTYPE');
                return (selectedField.fieldvalue == 1);
            case 'ADDR_FNAME':
                selectedField = this.dfs_look(node.children, 'ADDR_APPLICANTTYPE');
                return (selectedField.fieldvalue == 1 || selectedField.fieldvalue == 2);
            default: 
                //Perform specific action for default case
        }
    }

Answer №3

Give this a try

const isFieldVisible = (node: any, field: DocumentField): boolean => {

 let field:{
      tag: "ADDR_KOMU" | "ADDR_SNAME" | "ADDR_FNAME",
      fieldvalue:boolean
 };

 switch (field.tag) {
      case 'ADDR_KOMU':
      case 'ADDR_SNAME':
           field = this.dfs_look(node.children, 'ADDR_APPLICANTTYPE');
           return (field.fieldvalue == 1);
      case 'ADDR_FNAME':
           field = this.dfs_look(node.children, 'ADDR_APPLICANTTYPE');
           return (field.fieldvalue == 1 || field.fieldvalue == 2);
      default:
      return
 }

}

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

I'm encountering an issue where the database table in Postgres is not updating correctly while working with Node

Currently, I am working on a CRUD application where I can successfully read and delete data from the database table. However, I have encountered an issue when trying to update specific data for a particular route. Every time I attempt to update the data in ...

What could possibly be causing this element to shift side to side (in IE only) during the CSS animation?

UPDATE: Issue occurring on Internet Explorer 10, Windows 7 When using the transform property to adjust the horizontal position of an element during animation, the vertical value is updated as well. However, despite setting the horizontal value to the same ...

Best Practices for Updating UI State in Client Components Using NextJS and Server Actions

My goal is to create a page using nextjs 14 that functions as a stock scanner. This page will retrieve data from an external API using default parameters, while also offering users the ability to customize parameters and re-run the scan to display the resu ...

What steps do I need to take in order to ensure that when the word Hello is entered, the resulting output will display e:1, h:1, l:2, o:1

<!doctype HTML> <html> <body> <h3>Enter a string: </h3> <input id="myInput1" type="text"> <button onclick="count()">See output</button> //Click to see th ...

I'm experiencing a problem with my React application where errors are not being shown in the browser. Instead

Why is React only displaying an empty screen instead of showing errors like on my instructor's system? How can I resolve this issue? EDIT: While I can see the error in the console and IDE, I want to test error boundaries. When using error boundary a ...

JavaScript event/Rails app encounters surprising outcome

I have encountered a strange bug in my JavaScript code. When I translate the page to another language by clicking on "English | Русский" using simple I18n translation, my menu buttons stop working until I reload the page. I suspect that the issue ...

How can I reverse the names displayed in ng-repeat when I click?

When utilizing the orderby filter in angularjs, I want to be able to sort the data only when the button is clicked. If the button is not clicked, the sorting order should not be displayed. <tr ng-repeat="tools in toolsfilter | orderBy:orderByField:reve ...

Basic exam but located in a place that is not valid

Here is a test I am working on: // import {by, element, browser} from "protractor"; describe('intro', () => { beforeEach(() => { browser.get(''); }); it('should have multiple pages', () => { let buttonOn ...

What is the best approach for iterating through the creation of Objects?

Here is a simplified version of the current code, with fewer rows and properties. var row1 = new Object(); var row2 = new Object(); var row3 = new Object(); var row4 = new Object(); var row5 = new Object(); var row6 = new Object(); var row7 = new Object() ...

Clicking on the icon reveals the current date

I need some help with the input field that displays the calendar date. Currently, I can only click on the input field to show the calendar date. What I actually want is for users to be able to click on a calendar icon to display the calendar date, which sh ...

Storing a reference to children generated by a function within a child prop

I am currently working on a Feed component that accepts a data prop, consisting of an array of items, and a children prop intended for a function that maps the data to a DOM element. My current challenge is implementing the ability to scroll to any elemen ...

Using Typescript to create a generic return type that is determined by the type of a property within an object union

Consider the following scenario: type Setting = { key: "option_one", value: number, } | { key: "option_two", value: string, } export type SettingKey = Setting["key"]; // "option_one"|"option_two ...

Display information in real-time based on user input using Highcharts

I am trying to display data using highcharts on my index.php page. Can anyone help me with this?, here is what I have attempted so far: This is the HTML code I have: <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" cont ...

Challenges when upgrading from Ext JS 3 to Ext JS 4

I am looking to upgrade my code from Ext JS 3 to Ext JS 4. I used the Ext.Updater class in Ext JS 3, but I cannot seem to locate a similar functionality in Ext JS 4. Can anyone provide assistance with this transition? ...

onkeypress() method not triggering the function

I have a task to prevent users from typing "%" in a textArea, so I implemented the following: However, even after clicking inside the text area, I can still type '%', indicating that my onkeypress function is not working properly or there is an ...

Customized AngularJS URLs

After gaining proficiency in BackboneJS and AMD, I have successfully completed multiple large projects. Now delving into AngularJS, I have already implemented it with AMD and created controllers and services with ease. The only challenge I'm facing i ...

Adjust the column count in mat-grid-list upon the initial loading of the component

My goal is to implement a mat-grid-list of images with a dynamic number of columns based on the screen size. Everything works perfectly except for one small glitch – when the grid first loads, it defaults to 3 columns regardless of the screen size until ...

Issues with loading JavaScript in Selenium

I have been trying to extract data that is loaded through google tag manager. Despite my efforts using both chrome and firefox, the li elements I need in the body always appear empty no matter what timing I use. import undetected_chromedriver as uc from ...

Retrieve information from a database in real-time using Ajax without needing to set a refresh interval

Currently, I have been working on jquery/ajax requests and have managed to create an ajax request that retrieves data from a database. However, the issue at hand is that I am continuously utilizing window.setInterval() to refresh this function every x seco ...

I'm just starting out with jQuery and JSON and could use some assistance with formatting the string, specifically so I can properly iterate through it

This is the controller. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> @RequestMapping("/getDropDownAjax") public void fetchData(HttpServletRequest req,HttpServletResponse resp){ System.out.println ...