What is the best approach to streamline and optimize this JavaScript logic code for greater efficiency?

Working on a project, I find myself dealing with 21 buttons that can be in either an active or inactive state. The state of certain buttons is influenced by the press of other buttons as well as their own activation. To handle this in my HTML, I utilize ng-click to trigger a function named updateActiveButtons(num) which manages the activation and deactivation of specific buttons.

The approach I took involved creating an array with 21 elements, all initially set to false but updated upon button presses. However, I must admit that my code currently lacks elegance and there must be a more efficient way to structure it logic-wise.

Below is the implementation of my updateActiveButtons function:

/* Array for active buttons
0: Company Name 1: Country 2: Industry 3: Search 4: Company Name - Seller Name 5: Company Name - Buyer Name 6: Country - USA 7: Country - China 8: Country - Israel 
9: Country - Russia 10: Country - India 11: Country - Japan 12: Industry - Tech 13: Industry - Consumer 14: Industry - Pharma 15: Industry - Financial 16: Industry - Biotech 17: Industry - Industrial 
18: Date 19: Valuation 20: Industry - Business
*/
$scope.activeButtonArray = new Array(21);
for (var i = 0; i < $scope.activeButtonArray.length; i++) { $scope.activeButtonArray[i] = false; }
//pos = position in array
$scope.updateActiveButtons = function(pos) {
    console.log($scope.activeButtonArray[20]);
    if(pos != 0 || pos != 1 || pos != 2 || pos != 3 || pos != 4 || pos != 5) {
        $scope.activeButtonArray[pos] = !$scope.activeButtonArray[pos];
    } else if(pos == 3 && !$scope.activeButtonArray[pos]) {
        $scope.activeButtonArray[pos] = true;
    } else if(pos == 3 && $scope.activeButtonArray[pos]) {
        $scope.activeButtonArray[pos] = false;
    }
    // Additional if-else conditions for specific button interactions...
}

Taking a step back, I realize that my code contains a substantial amount of repetition, resulting in a less than optimal and professional outcome. If anyone has any recommendations on how I can improve this situation, I would greatly appreciate it.

Answer №1

One approach is to refactor extensive conditions or code blocks into separate methods/functions

For example, you can transform:

if ($scope.activeButtonArray[4] || $scope.activeButtonArray[5]) {
    $scope.activeButtonArray[0] = true;
}

into:

if (checkCondition($scope))

This method also improves readability and makes the code more self-explanatory.

Answer №2

Upon receiving pixelearth's suggestion, I decided to implement a new function as recommended.

The newly created function takes an array, a starting point, and an end point as arguments, and returns true if any of the values within that range in the array are true.

Below is the function:

var arrayContainsTrue = function(arr, start, end) {
    for(var i = start; i <= end; i++) {
        if(arr[i] == true) {
            return true;
        }
    }
    return false;
}

To optimize my code, I simply utilized the function with specific start and end points based on requirements:

if(!arrayContainsTrue($scope.activeButtonArray, 6, 11))

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

Perform a series of database queries one after the other, ensuring they are completed before

Although the database queries themselves are working fine, I am facing an issue with executing them sequentially in Node. Here is an example of the queries I need to execute in order: DELETE FROM myTable; INSERT INTO myTable(c1, c2, c3) VALUES (x, y, z); ...

Exploration Pointers for Foursquare Web Users

Why does my search suggestion keep returning '568 broadway' even after I have updated the authentication to my client id and client secret? Currently running on: https://api.foursquare.com/v2/venues/suggestCompletion?ll=40.7,-74&query=fours ...

When jQuery is combined with extending Object.prototype, the result is an error message that states, "c.replace is not

In my open source project, I am utilizing jQuery 1.5 and the following snippet is included in my JavaScript code: /** * Object.isEmpty() * * @returns {Boolean} */ Object.prototype.isEmpty = function () { /** * @deprecated Since Javascript 1.8 ...

Display a Google Map within a modal window following an Ajax request

I'm currently developing a website where I need to display a Google map inside a modal after an AJAX call. The modal is created using Bootstrap, but I'm facing an issue where the map remains blank once the modal is opened. An interesting observa ...

Is there a way to transform a large gltf file into jsx format?

I recently created a 3D scene in Blender and wanted to incorporate it into my React Three Fiber project. However, after exporting the scene to glTF format, I discovered that the file contained around 300k lines. The strange thing is that the file works per ...

Creating unique $scope variables for each item in an AngularJS ng-repeat array

I'm in the process of creating a food order form, and I'm facing an issue with attaching a list of options to individual item indexes instead of the parent. Currently, everything is functioning correctly, but when I add an option to one product i ...

Arrange divs in a grid layout with evenly distributed dynamic spacing

I am not a big fan of bootstrap, so I was wondering if it is possible to achieve the layout without using it. I have 6 divs that I want to arrange in 2 rows and 3 columns. I need the space between each row/column to be precise. While I can calculate this ...

Comparing elements in one array to elements in another array

In AngularJS, the $scope.categories array is populated from a multi-select element. $scope.categories = ["Adventure", "Strategy"] To compare this array with the categories in the items array below: $scope.items = [ { title: "Star Wars", ...

What is the best way to access and verify data from an array that has been passed through props

I am working with a component that takes an array as a prop <Component runners={['1','2']}/> Inside this functional component, my goal is to generate an element for each value in the array. Here's my logic: const { runners ...

Managing numerous callbacks for a specific route within Express.js

After going through the Express.js documentation, I came across a section discussing how to handle callbacks for routes using the syntax: app.get(path, callback [, callback ...]) However, I encountered difficulty in finding an example that demonstrates ...

How can I add an item to an array within another array in MongoDB?

I currently have a Mongoose Schema setup as follows: const UserSchema = new mongoose.Schema({ mail: { type: String, required: true }, password: { type: String, required: true }, folders: [ { folderName: { type: S ...

Tips for effectively utilizing axios without Vue.js CLI (for instance, in JS Fiddle)

Currently, I am immersing myself in the world of vue.js. To get a better understanding of the dependencies, I have chosen not to utilize the Vue cli just yet, opting for JS Fiddle instead. My next goal is to interact with an API using axios. Here is a glim ...

I am having an issue in AngularJS/Bootstrap where my cancel button is triggering the submit event. Can

My Angular and Bootstrap form includes a submit button and a cancel button to hide the form. However, I noticed that when I click on the cancel button, it first calls the cancel event handler and then proceeds to call the submit handler. Is this the expe ...

Is there a way to access just the concealed text within an element?

Is there a way to create a JavaScript function that can specifically extract hidden text from an element? Are there any existing libraries with this capability, and if so, how efficient are they? In order for an element to be considered visible ac ...

Updating token using an Ajax request in a PHP webpage

Currently, I am encountering an issue with my token system for requesting PHP pages via Ajax. The problem arises when attempting to make multiple Ajax requests from the same page as I am unable to refresh the token on the initial page. To elaborate furthe ...

Transfer information stored in a promise to the callback function of another controller

When Controller A sends a request via promise, what is the most effective method for running a callback function simultaneously in another Controller B? Is it best to broadcast via a service in the original callback and then listen for it in the other cont ...

What could be causing the props to appear empty in a Child component within a Quasar framework and Vue 3 application?

I am facing an issue while passing props to a Child component table in my Quasar Vue3 app. The content is not being rendered, and I can't figure out why. Strangely, the console is clear of any errors. In the parent component, I am creating an object w ...

Struggling with the development of a crossfading image gallery using jQuery's .animate() function while ensuring compatibility with IE8

Seeking assistance in creating a crossfading image gallery using jQuery and the .animate() function. I'm struggling to solve the issue of smooth fadeIn for the next image while maintaining compatibility with IE8. https://jsfiddle.net/Vimpil/fqhc1e9m/ ...

Monitoring progress with Angular $http and $q

Is there a method to monitor the progress of http requests using Angular's $http and $q services? I am sending multiple $http calls from a list of URLs and then utilizing $q.all to gather the results of all the requests. I want to keep track of the pr ...

How to efficiently create a unique object on MongoDB during the first instance

In the project I'm working on, there is a feature where a user can create a safe by visiting /mysafe. However, I want this safe to be created only once when they first visit the page. Subsequent visits should redirect them to /mysafe/theidofit. Have ...