JavaScript's counterpart to the Enum.HasFlag() method in .NET

In my .NET backend, I am utilizing HasFlag() to handle enum authorization.

Enum Foo {
  0: Zero,
  1: One,
  2: Two,
  3: Three,
  ..
}

5.HasEnum(Foo.One) is falsy because 5 is equal to 3 + 2
6.HasEnum(Foo.One) is truthy because 6 is equal to 3 + 2 + 1

What approach can be taken in JavaScript to achieve the same functionality?

I have a role value that falls within the range of > 0 and < 1048, how can I determine if it contains a role corresponding to 32?

Answer №1

extend global {
    interface Number {
        isFlagged(flag: number): boolean;
    }
}

Object.defineProperty(Array.prototype, 'isFlagged', {
    enumerable: false,
    writable: false,
    configurable: false,
    value: function (flag: number) { return (this & flag) === flag; }
});

Object.defineProperty(Number.prototype, 'isFlagged', {
    enumerable: false,
    writable: false,
    configurable: false,
    value: function (flag) { return (this & flag) === flag; }
});


document.querySelector("#output").innerHTML = "(3).isFlagged(1) = " + (3).isFlagged(1);
document.querySelector("#output").innerHTML += "<br>(4).isFlagged(1) = " + (4).isFlagged(1);
<div id="output"></div>

If you are using plain JavaScript, simply remove the declare global and ":number" signature.

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

Creating a text file while in a suspended state within the event handler on Windows 8 using HTML5

When the suspend event is triggered inside the winjs.application.oncheckpoint event handler, I am attempting to write a text file. The content of the file is my object in JSON format. Below is the code snippet: applicationData.localFolder.createFileAsync( ...

Measuring Meteor Activity Through Router-Level Subscriptions

My challenge involves managing a list that is subscribed to the 'posts' publication with a specified limit. Publication Meteor.publish('posts', function(options) { check(options, { sort: Object, limit: Number }); var po ...

Include div elements that are currently displayed in order to calculate the final total

I have a roster of divs that retrieve integer values from a SQL table. All these divs remain hidden until a specific choice is made in the form. I aim to establish an additional div that adds up all visible divs at the conclusion for the user to view their ...

How does JavaScript manage to be both non-blocking and asynchronous while also being single-threaded?

I'm struggling with understanding how Javascript can maintain a single-threaded nature while still being non-blocking on the client. My current mental model is akin to an assembly line: Imagine a single assembly line at the beginning of code execu ...

Click here to access the tab

Here's a question that might seem very basic. I've been using the tabs example found at http://www.w3schools.com/howto/howto_js_tabs.asp https://i.sstatic.net/E6PUG.png I'm curious about how to link from an external page to a specific open ...

Finding subsetsums in Javascript

I'm facing an issue with my JavaScript code that seems to be causing it not to run properly. <p id="demo"></p> Here is the JS code: function isSubsetSum(arr, n, sum) { if (sum == 0) { return true; } if (n == 0 && sum ...

What is the process for running a Threejs VR project with a local server?

I am attempting to test a threejs VR project on my Samsung NOTE 4 device using xampp local server. Surprisingly, the online threejs VR examples (https://threejs.org/examples/?q=vr#webvr_cubes) work perfectly on this phone. However, when I try to access th ...

Unable to display objects in the console window debugger for debugging purposes

When attempting to print the objects in the console window using the code below, I am receiving an "Undefined" error message. Any advice on how to resolve this issue? var details = [ { name:"Anita", age:"20" },{ name: "H ...

When the mouse is clicked, the character fails to reach the intended destination or moves in the wrong direction on the HTML canvas

UPDATE: RESOLVED I am currently working on a game where the character moves by right-clicking. The character is meant to walk slowly, not teleport, towards the destination set by right-clicking on the canvas. However, I have encountered an issue where the ...

Oops! Slim-loading-bar encountered an error because it was unable to locate the module '@angular/core'

I am currently learning Angular and attempting to integrate the ng2-slim-loading-bar. However, I encountered the following error - ERROR in ../node_modules/ng2-slim-loading-bar/index.d.ts(1,37): error TS2307: Cannot find module '@angular/core'. ...

Learn how to perform a post request in node js without triggering a page redirect or refreshing the form, all without using the preventdefault method

Is it possible to prevent the page from refreshing after sending data through an HTML form hitting a specific endpoint? I'm unsure about the best solution as there is no prevent default in nodejs, and I don't want the same page to redirect or re ...

Is there a more concise manner to represent the condition "if both a and b are true or if neither a nor b are true" in Javascript?

How can we convey the concept of both a and b being true or neither a nor b being true, meaning that the boolean values of a and b are identical? ...

What could be the reason for only one of my states being modified when I call my function?

Currently, I have a single state in React.js consisting of two key-value pairs for length validation and character validation: const [validation, setValidationState] = useState({ lengthValidation: "", characterValidation: "", }); These states are e ...

Transmit the canvas image and anticipate the AJAX POST response

I need to send canvas content to my API endpoint using ajax and wait for the response before moving on to the next function. Here is my current sending function: function sendPicture(){ var video = document.getElementById('video'); var canvas ...

Utilizing setState within the useEffect hook can lead to the application experiencing

Why does my code result in an endless loop error? This issue is pointing to the line marked with *: function Blog() { const [blog, setBlog] = useState({}); const query = useQuery(); async function fetchBlog(query) { const data = awai ...

Using React to iterate over a JSON object on a map

I'm struggling to figure out how to loop through the nested JSON data provided. My goal is to display the elements in a select option list. After making a request, I store the data in a state variable. const [filterData, setFilterData] = useState([]) ...

Interactive planetary visualization using three.js in real-time

As I work on my react project, I'm developing a globe and looking to initialize it accurately with respect to a specific time, whether it be the current time or a future time. The goal is for this globe to correctly align itself with the day and night ...

What steps should be taken to resolve the error message "EROFS: read-only file system, attempting to open '/var/task/db.json'?"

const jsonServer = require('json-server') const cors = require('cors') const path = require('path') const server = jsonServer.create() const router = jsonServer.router(path.join(__dirname, 'db.json')) const middlewa ...

"How can I extract father's details by clicking on a button

After clicking, I need to access the parent element. Here is the HTML code I have: <button mat-icon-button (click)="download($event)"> The generated HTML code is as follows: <button _ngcontent-wsc-c153="" mat-icon-button=&q ...

Triggering TypeScript error due to missing type annotations for arrays

When I type const array = [], TypeScript automatically infers it as any[]. I have been looking for a solution to make this fail linting, but so far I have not found any rule in either ESLint or TypeScript that can help with this. const array = []; //arra ...