What advantages do binary shifts offer in enums?

What do you think about this code snippet?

/**
 * Bitmask of states
 */
export const enum ViewState {
    FirstCheck = 1 << 0,      // result is 1
    ChecksEnabled = 1 << 1,   // result is 2
    Errored = 1 << 2,         // result is 4
    Destroyed = 1 << 3        // result is 8
}

I'm curious why the integer results were not explicitly stated as numbers 0,1,2,3. Any thoughts on this approach?

Answer №1

Reading lists may be simplified by utilizing bit shifting to quickly determine the value of an additional element. It's a matter of personal preference and efficiency for both the reader and the author.

Utilizing shifts allows for the combination of multiple states into a single value. For example, a combined value of 6 can represent being both Errored and ChecksEnabled.

var combined = ViewState.ChecksEnabled | ViewState.Errored;

var isChecksEnabled = (combined & ViewState.ChecksEnabled) == ViewState.ChecksEnabled;
// alternatively
var isChecksEnabled = !!(combined & ViewState.ChecksEnabled);

Answer №2

This enumeration represents the concept of four flags, each capable of being either activated or deactivated. By combining the desired values using a logical OR operation, you can assign a specific value to the enum. For instance:

z = ViewState.FirstCheck | ViewState.ChecksEnabled

Subsequently in the code, you can independently assess these values by performing a logical AND operation with the desired flag:

if (z & ViewState.FirstCheck) {
  do_something();
}

if (z & ViewState.ChecksEnabled) {
  do_something_else();
}

The best way to ensure clear separation and identification of individual flags within the enum value is to assign them as powers of two.

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

Error encountered while uploading a file with Fastify and Nestjs

I encountered an issue while attempting to upload a file to my nest.js server, receiving the following error message: Error: Unsupported Media Type: multipart/form-data; boundary=--------------------------140603536005099484714904 My approach was based ...

Can we separate city, state, and country data into individual input fields using Autocomplete and Geonames?

Currently, I have a single INPUT field set up to trigger the jQuery UI Autocomplete function, which pulls data from Geonames API. $( "#city_state_country" ).autocomplete({ source: function( request, response ) { $.ajax({ url: "http ...

Tips for retaining the scroll position of a particular page after a postback

I am working on a grid to display data row by row. Each row is displayed using a user control. When I scroll to the bottom of the page and click on a row, it redirects me to a view page for that specific row. However, when I click on the back link, I would ...

The AnimationMixer is refusing to start playing the animation from the gltf file

I have successfully imported a model using three.js and it works fine. Now, I am trying to run animations from a GLB file. Although I can retrieve the animation names with three.js, the TJS library fails to play my animations. GLB FILE There are two anim ...

When you set the href attribute, you are essentially changing the destination of the link

UPDATE: I'm not referring to the status bar; instead, I'm talking about the clickable text that leads to a link. /UPDATE I've gone through a few similar posts but couldn't find a solution. I have a link that needs to be displayed. www ...

What is the process for importing a jquery plugin like turnjs into a React component?

After searching through countless posts on stackoverflow, it seems like there is no solution to my problem yet. So... I would like to integrate the following: into my react COMPONENT. -I attempted using the script tag in the html file, but react does no ...

No data appears to be populating the Javascript data list, yet no errors are being displayed in

I'm facing an issue where I have data that I'm using to create two arrays, but they both end up empty without any errors in the console. Below is the data: mydata = { "id": "661", "name": "some name", "description": "some desc", ...

Creating a one-of-a-kind entry by adding a number in JavaScript

I am looking for a way to automatically add an incrementing number to filenames in my database if the filename already exists. For example, if I try to add a file with the name DOC and it is already present as DOC-1, then the new filename should be DOC-2. ...

Looping through a JSON object to create a table showcasing public holidays

Currently, I am working on creating a table that lists all the public holidays. The table comprises rows with holiday names on the left and dates on the right. Unfortunately, the table only displays data from the final array of the JSON object, whereas I ...

What is the best way to organize two separate arrays based on a single shared variable?

I have two separate arrays containing information. One array includes the title of each national park and other related data, while the second array consists of alerts from the entire NPS system. The common factor between these arrays is the parkCode. How ...

Discovering the specific value from a fixture file in Cypress

When I receive a JSON Response, how can I extract the "id" value based on a Username search? For instance, how can I retrieve the response with an "id" value of 1 when searching for the name "Leanne Graham"? It is important to note that the response valu ...

JavaScript: What is the concept of overriding function named params?

function retrieveData({item1 = "blue", item2 = 7}) { console.log('theItems'); console.log(item1); console.log(item2); } retrieveData( { item1: 'pink', item2: 9 } ); I've come across conflicting i ...

Utilize Vue.js to take screenshots on your device

After following the tutorial at https://www.digitalocean.com/community/tutorials/vuejs-screenshot-ui, I was able to successfully capture a screenshot with Vue.js. However, it seems that the dimensions of the screenshot are not quite right. Issue: The cap ...

Is the original image source revealed when clicked?

I've implemented an expand and collapse feature using jQuery/JavaScript. Clicking on the DIV causes the image inside to change state. However, clicking on the same DIV again doesn't return the image to its original state; it remains stuck in the ...

Utilizing JavaScript to bring JSON image data to the forefront on the front-end

In my quest to utilize JavaScript and read values from a JSON file, I aim to showcase the image keys on the front-end. To provide clarity, here's an excerpt from the JSON dataset: { "products": {"asin": "B000FJZQQY", "related": {"also_bought": ...

Retrieve the value of the specific element I have entered in the ngFor loop

I've hit a wall after trying numerous solutions. Here is the code I'm working with: HTML: import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styl ...

Having trouble with AngularJS? Ng-switch not updating after ng-click?

Initially in my code, I check if a user has the ability to flag a discussion. If they do, I use ng-switch where upon flagging, a success message is displayed: <div ng-if="canFlag(discussion)"> <div ng-switch="isFlagging" ng-click="fla ...

Navigate the div with arrow keys

Looking for an answer similar to this SO post on moving a div with arrow keys, could a simple and clear 'no' be sufficient: Is it possible to turn an overflowing div into a "default scroll target" that responds to arrow-up/down/page-down/space k ...

Move the option from one box to another in jQuery and retain its value

Hey guys, I need some assistance with a jQuery function. The first set of boxes works perfectly with the left and right buttons, but the second set is not functioning properly and doesn't display its price value. I want to fix it so that when I click ...

Having difficulty deleting an entry from a flatList in a React Native component when using the filter method

I'm currently facing an issue with deleting an item from my flatlist in React Native. I've been attempting to use the filter method to exclude the list item with the ID entered by the user for deletion, but it's not working as expected. I&ap ...