Eliminating redundancy in nested conditions

How can a nested conditional like the one below be optimized for improved performance and readability? To enhance efficiency, it would be beneficial to consolidate repetitive entries into a more practical function due to loops within many potential cases.

//a is set to 1, 2, or 3
//b is either true or false

for(var i=0; i<hugeNumber; i++){
switch(a){
    case 1:
        if(b){
            for(objects in longlist){
                objects.color = object.c;
                objects.position = object.x
            }
        }else{
            for(objects in longlist){
                objects.color = object.c;
                objects.position = object.y
            }
    case 2:
        if(b){
            for(objects in longlist){
                objects.color = object.b;
                objects.position = object.x;
            }
        }else{
            for(objects in longlist){
                objects.color = object.b;
                objects.position = object.y;
            }
    case 3:
        if(b){
            for(objects in longlist){
                objects.color = blackColor;
                objects.position = object.x;
            }
        }else{
            for(objects in longlist){
                objects.color = blackColor;
                objects.position = object.y;
            }
}
}

Adding conditionals within an overarching for loop seems equally unreasonable.

It would be ideal to define the target variable at the start when the conditions are known - where condition a always determines color c for 0, color b for 1, and blackColor for 2, while condition b always dictates position x for true and position y for false.

I have encountered similar questions regarding PHP and Ruby, but adapting solutions to JavaScript poses some challenges. While there are potential strategies, I have not yet been able to execute syntactically correct code.

UPDATE / SOLUTION: After receiving input, I found that this task can be efficiently accomplished using eval():

var targetColor;
var targetPosition;

switch(a){
    case 1: targetColor = "objects.c"; break;
    case 2: targetColor = "objects.b"; break;
    case 3: targetColor = "blackColor"; break;
}
if(b){
    targetPosition = "objects.x";
}else{
    targetPosition = "objects.y";
}

for(var i=0; i<hugeNumber; i++){
    for(objects in longlist){
        objects.color = eval(targetColor);
        objects.position = eval(targetPosition);
    }
}

If there is a better alternative to this approach, I am open to additional suggestions as I am aware of the potential risks associated with using eval.

Answer №1

Not as condensed, but still easy to understand and avoids unnecessary rechecks:

let axis = isHorizontal ? 'x' : 'y';
let color = '';
switch(type){
    case 1: color = 'red';
    case 2: color = 'blue';
    // more cases can be added...
}
for(item in itemList) {
    item.color = item[color] || 'black';
    item.position = item[axis];
}

Answer №2

let applyColorAndPosition = (valA === 0 ? "c" : (valA === 1 ? "b" : "blackColor"));
let positionType = valB ? "x" : "y";

for(items in itemList) {
    items.color    = applyColorAndPosition;
    items.position = positionType;
}

If you can include the code within the for loop, it might help with optimization.

Answer №3

Based on the logic you've outlined, I believe this strikes a good balance between conciseness and readability.

for(item in lengthyList) {
    item.position = condition ? x : y;
    switch(variable) {
        case 1: item.color = customColor;
        case 2: item.color = baseColor;
        case 3: item.color = backgroundColor;
    }
}

Does that explanation make sense to you?

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 for me to smoothly switch between two nuxt pages, pausing for a child component transition or animation to complete before moving on?

Seeking guidance on transitions. Is it feasible to wait for a child transition/animation to finish before transitioning from one page to another? For instance: 1) Home (Page Component) a) Logo (Vue Component) 2) About (Page Component) Upon clicking on ...

Tips for Retrieving Array Values into Individual Variables

When working with AJAX and receiving a response in JSON format, I am unsure of how to separate each array format into individual variables. Here is the response: final_string = [{"stars":1,"q1":0,"q2":0,"q3":0,"q4":0,"q5":0,"q6":0,"q7":0,"q8":0,"q9":0 ...

jQuery Load - Oops! There seems to be a syntax error: Unexpected token <

Error: Uncaught SyntaxError: Unexpected token < I encountered the error message mentioned above while trying to execute a jQuery load function: $('#footer').load(UrlOfFooterContent); The variable UrlOfFooterContent holds the URL of an MVC c ...

Button to close Jquery Dialog

I've set up a custom alert UI using jQuery UI, but I'm having trouble getting the close button to work properly. Here's my code snippet where I'm trying to override the default alert() function with jQuery UI dialog as described in this ...

Accessible Drag and Drop Pattern without Barriers

With the rise of ajaxish Web2.0, I question the feasibility of creating web pages that are 100% barrier-free. Are there established patterns to support common Web2.0 practices? I've been thinking about drag and drop functionality. Is there a universa ...

Trouble with mouseout listener in Wordpress causing Google Map to malfunction

Having trouble integrating a map into my WordPress site using the Google Maps API v3. The issue I am facing is that the listener assigned to the mouseout event is not functioning properly. I have copied and pasted the code from another website where it was ...

Problems with Searching in Bootstrap Tables

I'm experiencing a basic bootstrap error. I attempted to create a searchable table using this example: Unfortunately, the search function is not working when applied to my table. The table appears fully populated, but entering search terms like "CRY" ...

Trouble arises when trying to create an auto suggest text box using PHP and Javascript

I've been working on creating a basic auto-suggest input feature that connects to a MySql database to retrieve data. However, I'm facing a particular issue where when I enter the name of an object that I know exists in the database, the input bar ...

Creating a dynamic form with jQuery and assigning unique names to two different inputs

Currently, I am working on a program that necessitates adding a text box and textarea dynamically to a form. To achieve this, I am utilizing the clone function. Unfortunately, I have hit a roadblock in assigning unique IDs to each box. Below is the Jquery ...

What is the process for converting to the optimal prefix with js-quantities?

I am working with a value of `1200000 mm' and I want to find a method that can automatically convert it to the best prefix. For example: import Qty from 'js-quantities' const qty = new Qty(1200000, 'mm').toBest() // will be conve ...

Maintaining the dropdown in the open position after choosing a dropdown item

The dropdown menu in use is from a bootstrap framework. See the code snippet below: <li id="changethis" class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown>LINK</a> <ul class="dropdown-menu"> <li id ...

What is the reason behind the android code being incompatible with IOS operating systems?

I'm encountering an issue where a particular code is working on Android, but not on IOS. The code in question involves using JavaScript to differentiate the items in a list within an HTML select tag. It's perplexing to me how the code can operat ...

Retrieving information from an API and presenting it as a name with a link to the website

I am attempting to retrieve information from an API and present it in the format Name + clickable website link. Although I have managed to display the data, the link appears as text instead of a hyperlink. Here is my Ajax script: $(function() { ...

Is there a way to move an image from HTML to Node.js so that it can be utilized with EJS?

Currently working on building a fresh website with nodejs and expressjs. The main page (/home) includes a form with a file input. I've managed to code the preview of the image once it's uploaded... Now, I need help transferring the "link" of the ...

The Allman style is not applied by ESLint in VSCode to all languages, such as JSON

My disdain for Prettier stems from the fact that it restricts my freedom to utilize my preferred brace style. In my workflow, I rely on tools like CSSComb, PHP CS Fixer, and SCSS Allman Formatter as they support Allman style. While VSCode offers native Ja ...

What is the best way to send variables from JavaScript to PHP while utilizing Ajax technology?

While I have noticed similar questions like this one before, I want to address my specific concerns. In previous examples, the questioner referred to using Ajax in a format similar to this: $.ajax({ type: "POST", url: 'logtime.php', ...

Unraveling a binary file to an mp3 format with the power of Node.js

When attempting to encode an MP3 file to Base64 in Node.js using the following method: encodebase64 = function(mp3file){ var bitmap = fs.readFileSync(mp3file); var encodedstring = new Buffer(bitmap).toString('base64'); fs.writeFileS ...

Utilize [markdown links](https://www.markdownguide.org/basic-syntax/#

I have a lengthy text saved in a string and I am looking to swap out certain words in the text with a highlighted version or a markdown link that directs to a glossary page explaining those specific words. The words needing replacement are contained within ...

The :first selector examines the parent's parent as a reference point, rather than the immediate

I am facing a challenge with shuffling large elements within my layout because of floating them and attempting to display them. Specifically, the elements with the class .gallery-large always need to be the first child inside the .item container. There are ...

Reordering CRUD operations in AngularJS

I am currently working with this function: // Check if the object already exists. // If it does, the object is deleted and then created again. save: function(url, obj, errors) { this.get(url, obj); this.create(url, obj, errors); }; Despite the or ...