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

Ways to simulate file operations in sinon?

I have a function that unzips a file from the directory, and it is working perfectly fine. index.js const unZip = async (zipFilePath, destDir) => { await util.promisify(fs.mkdir)(destDir); return new Promise((resolve, reject) => { fs.create ...

Why does the request body show as null even after passing body data in Prisma?

My application uses Prisma for database storage with MySQL. It is built using Next.js and TypeScript. I have set up the API and it is functioning properly. However, when I try to save data sent through the API, the `request.body` is null. Interestingly, wh ...

What is the correct way to set up a custom class instance with specific parameters at the top level?

Is it possible to utilize the defineString(), defineInt, ... functions within a top-level custom class constructor? defineString() returns a StringParam object which has a value() method. I am looking to use parameterized configuration to initialize an in ...

What could be causing the malfunction of the Facebook iframe like button?

Even though it functions offline, there seems to be an issue with its performance online. Here is the code that was used: <iframe src="http://www.facebook.com/plugins/like.php?app_id=125925834166578&amp;href=http%3A%2F%2Fwww.facebook.com%2FBaradei. ...

Strategies for setting the output value for a defined generic type

Is there a way to create a function that accepts optional properties common across different types, while also requiring specific properties based on the generic type passed in? type Diff<T, U> = T extends U ? never : T type DiffTypes<T, U> = ...

Is there a way to convert Firebase JSON into a JavaScript object? If so, what is the method to

I am currently working on using the kimono web scraper in conjunction with Firebase to obtain data stored as JSON. To convert the JSON to XML, I am utilizing a JavaScript library which allows me to create a variable from the JSON file (an example is shown ...

Error message displaying "Invalid ID attribute in HTML 5 input"

On my website, I have a page with multiple items, each containing an HTML5 input field. Whenever a user changes the value of the input, it triggers an AJAX call to the server. The server then responds with JSON data, including an array of items that have ...

What is the best way to swap out elements in my string with those from an array?

Struggling to replace special characters in file names before saving them to the Windows filesystem due to compatibility issues. For my initial approach, I used the replace() method repeatedly on the string to replace specific special characters. Here&apo ...

The overlay background is being obscured by surrounding elements

Hey there! I'm experimenting with some basic coding and ran into an issue with an overlay. Here's the site link: Sorry for the strange language. :-) If you click on the button with the tiny icon, you'll notice that the overlay form isn&apos ...

I encounter Error 406 and CORS issues when making API calls

I am currently engaged in a project aimed at helping my employer keep track of shipping loads, customers, carriers, and locations. The frontend is built using a react app that enables users to input information regarding loads, customers, etc. On the backe ...

What is the process for incorporating a custom script into a pre-existing node.js library?

I am facing a challenge with integrating a personal script with custom functions into my local copy of the hls.js library. How can I successfully add a new script to the library and then utilize the functions written within it? To provide context, let&apos ...

Concatenate data received from PHP to a JavaScript variable and return it

In my current app development project, I have the following code snippet. The variable valdat is sent to a specified URL, processed through a PHP file, and then returned to the app. How can I add the data displayed in the alert message to another variabl ...

List out the decorators

One query is bothering me - I am attempting to create my own version of Injectable and I need to determine if a specific decorator exists in my Class. Is there a way to list all decorators of a class? Let's take the example below. All I want to know i ...

Exploring the Mathematical Capabilities of jQuery

I have a question regarding a jQuery code that retrieves the price of Bitcoin from a JSON API and displays its current value in euros. I am interested in converting this to another currency, such as Danish Crown or any other. Essentially, my query is whe ...

Using AngularJS to Bind HTML Safely: Understanding ngBindHtml and 'unsafe' HTML

I am facing an issue with displaying HTML content containing inline styling in my view. The code I currently have is: <div ng-repeat="snippet in snippets"> <div ng-bind-html="snippet.content"></div> </div> Unfortunately, all of ...

Guidelines for utilizing NgFor with Observable and Async Pipe to create Child Component once the data has been loaded

Encountering an issue while attempting to display a child component using data from an Observable in its parent, and then utilizing the async pipe to transform the data into a list of objects for rendering with *NgFor. Here's what I've done: C ...

ADVENTURE BLOCKED - Intercept error: net::ERR_BLOCKED_BY_CLIENT

I've encountered an issue where my initialize function doesn't run properly when a user has an ad blocker enabled. It seems that the ads-script.js file is being blocked by the client with a net::ERR_BLOCKED_BY_CLIENT error, leading to my .done ca ...

What could be causing my Apollo useLazyQuery to be triggered unexpectedly within a React hook?

import { useLazyQuery } from '@apollo/client'; import { useEffect, useState } from 'react'; import { ContestSessionResponseInfoObject, GetSessionDocument, HasAccessToRoundDocument, } from '@/graphql/generated/shikho-private- ...

encountered an issue while accessing a FastAPI-based API

While developing a login feature in Next.js, I encountered an issue when making a request to an API created in FastAPI to retrieve a cookie. The problem arises during the fetch operation on the frontend specifically when setting credentials to 'includ ...

The Unit Test for Angular NgRx is not passing as expected

I'm facing difficulties with my unit tests failing. How can I verify that my asynchronous condition is met after a store dispatch? There are 3 specific checks I want to perform: 1/ Ensure that my component is truthy after the dispatch (when the cond ...