Revamp the switch-case statement in JavaScript code

Is there a way to refactor this code in order to prevent repeating dailogObj.image? I would have used a return statement if it wasn't for case 5 where two assignments are required.

getDialogData(imageNum): any {

    const dailogObj = {
      image: '',
      buttonName: 'Learn More'
    };

    switch (imageNum) {
      case 1:
        dailogObj.image = '../../../assets/images/Red-Image.png';
        break;
      case 2:
        dailogObj.image = '../../../assets/images/blue-image-orgl.png';
        break;
      case 3:
        dailogObj.image = '../../../assets/images/Green-Image-2.png';
        break;
      case 4:
        dailogObj.image = '../../../assets/images/Gold-Image.png';
        break;
      case 5:
        dailogObj.image = '../../../assets/images/green-img-orgl.png';
        dailogObj.buttonName = 'Read Her Story';
        break;
      case  6:
        dailogObj.image = '../../../assets/images/Red-Image-2.png';
        break;
      case  7:
        dailogObj.image = '../../../assets/images/Blue-Image-2.png';
        break;
      case 8:
        dailogObj.image = '../../../assets/images/Gold-Image-2.png';
        break;
    }

    return dailogObj;
}

Answer №1

To enhance readability, consider separating the assignment into its own condition and utilizing an array to set the image property:

getDialogData(imageNum): any {
    const dialogObj = {
      image: '',
      buttonName: 'Learn More'
    };

    // Handle the default case if imageNum is not within the range [1..9]
    if (imageNum >=1 && imageNum <=9) {
        // Special handling for image number 5
        if (imageNum == 5) {
            dialogObj.buttonName = 'Read Her Story';
        }

        // If it falls within the range, select the appropriate image:
        var images = 
            ['../../../assets/imfages/Red-Image.png',
             '../../../assets/images/blue-image-orgl.png',
             '../../../assets/images/Green-Image-2.png',
             '../../../assets/images/Gold-Image.png',
             '../../../assets/images/green-img-orgl.png',
             '../../../assets/images/Red-Image-2.png',
             '../../../assets/images/Blue-Image-2.png',
             '../../../assets/images/Gold-Image-2.png']; 

        dialogObj.image = images[imageNum - 1];
    }
    return dialogObj;
}

Answer №2

images = {
    1: '../../../assets/pictures/Red-Photo.png',
    2: '../../../assets/pictures/blue-photo-orgl.png',
    ...
    8: '../../../assets/pictures/Gold-Picture-2.png'
};

dialogObject.image = images[imageNum];
dialogObject.buttonLabel = imageNum == 5 ? 'Explore Her Story' : 'Discover More';

You also have the option to create an additional object for storing button labels, similar to how image paths are stored.

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

Is there a way to simultaneously call two APIs and then immediately call a third one using RXJS?

I am looking to optimize the process of making API calls by running two in parallel and then a third immediately after both have completed. I have successfully implemented parallel API calls using mergeMap and consecutive calls using concatMap, but now I w ...

Changing the size of an iframe and closing it by pressing the ESC

I am developing an application that requires the ability to resize an iframe. When the user clicks the "Full Screen" button, the iframe should expand to occupy the entire screen. The iframe should return to its original size when the user presses the "Es ...

Enhance the connectivity of Angular js by activating the link function post transclusion

I am facing an issue with Angular where I have two directives that need to be transcluded within each other. However, I am unable to access the DOM using a simple JQuery selector after the transclude function has been executed. Specifically, I need to comp ...

Troubleshooting Problem: Difficulty with Uploading High-Resolution Images in Angular using

Currently, I am working on implementing file uploads using the combination of express.js, node, and angular. Everything seems to be functioning well when dealing with small image files. However, I encountered a 404 error when attempting to upload larger im ...

Executing a Select Change in a React Application using CasperJS

Has anyone else encountered difficulties with this issue? I have a basic React page set up, with a simple component that renders a select element and triggers a callback function when the value changes. Here is the basic structure of the component: const ...

Is there a way to use jQuery to eliminate divs that contain multiple identical data values?

Is there a way to accomplish this? <div class="chat_timestamp_group" data-date="08-March-2016"></div> <div class="chat_timestamp_group" data-date="08-March-2016"></div> <div class="chat_timestamp_group" data-date="14-March-2016" ...

When you're downloading a file in Safari, the filename ends up being displayed as 'unidentified'

I am encountering an issue with the code I implemented that downloads a file in Safari, but the filename appears as 'untitled'. Interestingly, it works fine in other browsers. var saveData = (function () { var base64 = "data:application/mswo ...

Changing the default download directory in Selenium using JavaScript

How can I use JavaScript to change the default download directory? I have a list of folders and one is named "C:\Study\Selenium". How do I update the location for downloaded files to this specific path in my code? chromeOptions.setUserPreference ...

Combining the value of $(this) to create an identifier name

I am attempting to create a hover effect on an h1 element that triggers the glowing effect on a span element with an id that corresponds to the value of the h1. While I have successfully set up a glowing effect for a sentence, I am struggling to replicate ...

What is the best way to ensure the height and width of a Next.js image matches the dimensions of the original image?

Currently, I am working on setting up an image gallery with a layout similar to Masonry. This layout involves multiple columns, all with the same width, adjusting based on the viewport width. The height of each item in the gallery is flexible, depending on ...

Angular: How to Disable Checkbox

Within my table, there is a column that consists solely of checkboxes as values. Using a for loop, I have populated all values into the table. What I have accomplished so far is that when a checkbox is enabled, a message saying "hey" appears. However, if m ...

Enhance Your NestJS Experience: Using Interceptors for Mapping and Error Handling

I'm looking for a NestJS interceptor that can log requests in all scenarios, including both successful executions and errors. Below is an example implementation: public intercept(context: ExecutionContext, next: CallHandler): Observable<any> { ...

Step-by-step guide on how to display chosen values in a multi-select dropdown menu

How can I dynamically select values in a multi-select box based on an array using Vue.js? I've attempted a solution but it's not working as expected. Any suggestions or help would be greatly appreciated. <div id="app"> <select class="m ...

Avoiding the issue of multiple submissions in Ajax forms

My website's contact form sometimes experiences a delay in sending submissions. When users, in their impatience, click the submit button multiple times, it results in the form being sent repeatedly to the host. To address this issue, I attempted to ...

Safari: Fixed-positioned DIVs staying put after DOM updates

Hey there! I've been experimenting with animating absolutely positioned DIVs on my webpage using some JavaScript to update the top and left CSS properties. It's been working smoothly in Chrome, Firefox, and even Internet Explorer 8. However, I e ...

Comparing the syntax of JSON to the switch statement in JavaScript

I recently came across a fascinating post on discussing an innovative approach to utilizing switch statements in JavaScript. Below, I've included a code snippet that demonstrates this alternative method. However, I'm puzzled as to why the alter ...

The responsiveness of Slick Slider's breakpoints is malfunctioning

After implementing a slider using slick slider, I encountered an issue with the width when testing it online and in a normal HTML file. If anyone could assist me in resolving this issue, I would greatly appreciate it. Please inspect the code for both scen ...

Is it possible to track unsuccessful email deliveries using MailApp?

In my Google Script program, I incorporate MailApp in the following manner: MailApp.sendEmail(AddressStringGlobal,EMailSubjectProperLanguageGlobal,"",{htmlBody: EMailBody}); The issue arises when I encounter a bad email address in my data set, causing my ...

Utilize Babel transpiling specifically for necessary Node modules

My current setup in nextjs is configured to handle ES6 code for IE11. module.exports = { poweredByHeader: false, distDir: "ssr_build", webpack(config) { config.node = { fs: "empty", net: "empty", tls: "empty" } config.plugins = config.plugi ...

Issue with cross-origin in Salesforce reply (Access-Control-Allow-Origin)

While attempting to retrieve records from Salesforce using external local files via JS, I encountered an issue. Although I can see a response in the network tab, the console displayed the following error message: "XMLHttpRequest cannot load . No 'A ...