Is there a more efficient method to optimize this code and eliminate the need for multiple if statements?

Looking for advice on refactoring this code to reduce the number of if statements. The challenge is handling 4 different inputs to generate a single answer.

const alert= markers.some((marker) => marker['hasAlerts'] > 0);
const warning= markers.some((marker) => marker['hasWarnings'] > 0);
const isCurrentHourAlert = markers.some((marker) => marker['isCurrentHourAlert'] > 0);
const isCurrentHourWarnings = markers.some((marker) => marker['isCurrentHourWarnings'] > 0);

        let style = determineStyle(isCurrentHourAlert, isCurrentHourWarnings, alert, warning);

function determineStyle(hasHourAlert, hasHourWarning, hasAlert, hasWarning) {
    if (hasHourAlert && hasHourWarning) {
        return 4;
    } else if (hasHourAlert) {
        return 4;
    } else if (hasHourWarning) {
        return 5;
    } else if (hasAlert && hasWarning) {
        return 2;
    } else if (hasAlert) {
        return 2;
    } else if (hasWarning) {
        return 3;
    } else {
        return 1;
    }
}

Attempted to use switch case statement but still ended up with complex validation in the code.

Interested in exploring patterns or structures that could simplify readability and refactoring of the code.

Answer №1

To improve efficiency, a function can be created to iterate through the markers and check for the desired property.

The code currently sets style = 4; regardless of whether isCurrentHourAlert is true, eliminating the need for the first conditional branch completely.

const markersHas = prop => markers.some(marker => marker[prop] > 0);
let style = 0;
if (markersHas('isCurrentHourAlert')) {
    style = 4;
} else if (markersHas('isCurrentHourWarnings')) {
    style = 5;
}
// etc

If preferring to use a switch statement:

switch (true) {
  case markersHas('isCurrentHourAlert'):
    style = 4;
    break;
  case markersHas('isCurrentHourWarnings'):
    style = 5;
    break;
  // etc

An alternative approach involves using an array of conditions and associated styles, iterating through to find the first true condition and setting the style accordingly.

const styleConds = [
    [markersHas('isCurrentHourAlert'), 4],
    [markersHas('isCurrentHourWarnings'), 5],
    // etc
];
const styleCond = styleConds.find(cond => cond[0]);
const style = styleCond?.[1] ?? 0;

Consider avoiding magic numbers by using more descriptive identifiers instead. For instance, the line style = 4; may be unclear at first glance - what does 4 represent?

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

The ESLint tool seems to be struggling to detect the package named "@typescript-eslint/eslint-plugin"

Struggling with getting ESLint to function properly on a new Angular project in VS Code. The error message I keep encountering is about failing to load "@typescript-eslint/eslint-plugin". After spending the past 3 hours troubleshooting, I have searched hig ...

Is there a faster way to create a typescript constructor that uses named parameters?

import { Model } from "../../../lib/db/Model"; export enum EUserRole { admin, teacher, user, } export class UserModel extends Model { name: string; phoneNo: number; role: EUserRole; createdAt: Date; constructor({ name, p ...

The NgModel function within *ngFor is executing more times than necessary during initialization

Displayed on screen are a list of tutorials with check boxes next to each tutorial's states. These tutorials and states are pulled from the database, each tutorial containing a name and an array of associated states. Here is the HTML code: <div c ...

What is the best way to declare and initialize a global variable in a TypeScript Node application?

When using Webpack: const WebpackConfig = { // ... plugins: [ new Webpack.DefinePlugin({ __IS_DEVELOPMENT_BUILDING_MODE__: isDevelopmentBuildingMode, __IS_TESTING_BUILDING_MODE__: isTestingBuildingMode, __IS_PRODUCTION_BUILDING_MO ...

Every time I clear the information, it seems to be instantly replaced with new data. How can I prevent it from constantly refilling?

When I press the remove button on my application, it successfully deletes the data in a field. However, it also automatically adds new data to the field which was not intended. I am seeking assistance on how to keep those fields empty after removing the ...

Is there a way to deactivate the click function in ngx-quill editor for angular when it is empty?

In the following ngx-quill editor, users can input text that will be displayed when a click button is pressed. However, there is an issue I am currently facing: I am able to click the button even if no text has been entered, and this behavior continues li ...

The error code TS2554 is triggered when the function expects between 1 to 2 arguments, but receives

When attempting to include { useHash: true } in RouterModule.forRoot, I encountered the following error. How can I add additional arguments? @NgModule({ imports: [RouterModule.forRoot( appRoutes, { enableTracing: true }, // <-- for debugging ...

The type declaration for the Storage.prototype.setObject method

I'm facing a challenge in creating a d.ts file for the given DOM feature. Storage.prototype.setObject = function(key:string, value:any) { this.setItem(key, JSON.stringify(value)); } Storage.prototype.getObject = function(key:string) { var va ...

Conceal or remove disabled years in Angular Material datepicker

I previously disabled years prior to 2018, but now I would like to hide or delete them. The year selection range currently starts from 1998, but it should begin at 2018 instead. Is there a way to display only 3-4 years instead of the current 24-year rang ...

Jest: Test fails due to import statement in node_module dependency

Short Version I'm experiencing a crash in my Jest test due to a SyntaxError related to an import statement outside a module. The issue arises from a node_module that uses the import statement. How can I resolve this error? Situation Overview In deve ...

Tips for effectively managing index positions within a dual ngFor loop in Angular

I'm working on a feedback form that includes multiple questions with the same set of multiple choice answers. Here's how I've set it up: options: string[] = ['Excellent', 'Fair', 'Good', 'Poor']; q ...

Property finally is missing in the Response type declaration, making it unassignable to type Promise<any>

After removing the async function, I encountered an error stating that the Promise property finally is missing when changing from an async function to a regular function. Any thoughts on why this would happen? handler.ts export class AccountBalanceHandle ...

Generating HTML components dynamically using strings in TypeScript

Is there a way to define a prop that can accept either a ComponentType or a string? Consider the code snippet below. interface MyComponentProps { Component: React.ComponentType } const MyComponent: React.FC<PropsWithChildren<MyComponentProps> ...

Ways to update the state of an array without clearing the existing array items

I am attempting to add fetched array items to an existing state that already contains items (with plans to include pagination). However, when I try using code similar to setMovies((prevMovies) => [...prevMovies, ...arr1]), I encounter a Typescript erro ...

The Axios GET method retrieves a response in the form of a string that represents an object

I have developed a function that triggers an axios Request. I am working with typescript and I am avoiding the use of any for defining return data types of both the function and the axios request itself. The issue arises when the returned object contains ...

Tips for transforming switch statements in JSX

I'm looking to refactor the switch statement in my JSX code to make it more DRY. The goal is to render different buttons based on different cases. For cases 'C' or 'TV', I need to render two buttons ('awake' and 'asl ...

The journey of communication: uncovering the essence of @input between parent and

I'm diving into Angular and currently working on the @Input phase. Within my main app, there's a child component. Inside app.component.ts, I've declared a test variable that I wish to pass from app.component.ts to child.component.ts. // ap ...

Can I combine tuple types in Typescript?

type A1 = ['x','y','z'] type A2 = ['u','v','w'] type AN = [.., .., ..] type C = Combine<A1,A2,...,AN> //or Combine<[A1,A2,...,AN]> //resulting in ['x','y','z& ...

What are the best practices for implementing Alertify in a Typescript project?

I'm relatively new to Angular2 so please bear with me. I attempted to implement Alertify.js in my Angular2 project for a custom dialog box, but I am encountering difficulties getting Alertify to work properly. Since I lack deep knowledge of JavaScrip ...

Encountering a "Error: Uncaught (in promise): EmptyError: no elements in sequence" due to the presence of multiple Angular 9 Route Resolvers

Why do I encounter an error when attempting to use multiple resolvers in Angular routing? If I remove one of the route resolves, everything works fine. But as soon as I include both, the error occurs. https://i.stack.imgur.com/WFI5C.png https://i.stack.im ...