Create enumeration keys by adding up enumeration values for permissions

One example of an enum is:

RoleEnum={
            None: 0,
            ViewAnalytics: 1,
            ManageTargets: 2,
            ManageBranches: 4,
            ViewActivationDetails: 8,
            ManageUsers: 16,
            ViewBilling: 32,
            ManageQuestions: 64
};
  1. If the response from the database is 7, then it should return:
    ["None","ViewAnalytics","ManageTargets","ManageBranches"]
  2. If the response from the database is 3, then it should return:
    ["None","ViewAnalytics","ManageTargets"]

This logic applies to other cases as well.

In a .ts file, you can have:-

      vm.userLevelPermission.ViewAnalytics = vm.userLevelPermission.includes('ViewAnalytics');
      vm.userLevelPermission.ManageTargets = vm.userLevelPermission.includes('ManageTargets');

The permission value received from the database is added here with the logic.

    <div class="panel-title"><h4 class="mts">User Level Permission Settings<button class="btn btn-primary pull-right" type="button" ng-click="vm.updateUserLevelPermission()">Save</button></h4></div>
</div>
        <tr>
            <td>Manage Targets</td>
            <td class="text-center"><input type="checkbox" class="css-checkbox" checked="vm.userLevelPermission.ManageTargets"></td>
            <td>View Analytics</td>
            <td class="text-center"><input type="checkbox" class="css-checkbox" checked="vm.userLevelPermission.ViewAnalytics"></td>
        </tr>

Similarly, when updating, the value should be the sum of checked boxes. If both are checked, it will return 3.

Answer №1

Perhaps you just need to adjust your approach a bit. Instead of overcomplicating things, consider using a simple bitmask technique. Here's a snippet of code that demonstrates how it can be done:

const permissions = { None: 0, ViewAnalytics: 1, ManageTargets: 2, ManageBranches: 4, ViewActivationDetails: 8, ManageUsers: 16, ViewBilling: 32, ManageQuestions: 64 };
const userPermissions = 7; // for example

const userLevelPermissions = Object.fromEntries(Object.entries(permissions).map(([key, value]) => {
    return [key, key === 'None' || !!(userPermissions & permissions[key])];
}));

const hasPermission = (permission) => permission === permissions.None || !!(userPermissions & permission)

console.log(hasPermission(permissions.ManageTargets))

console.log({userLevelPermissions})

Answer №2


vm.userLevelPermission = Object.keys(vm.userLevelPermissionsEnum).map(function(key, value) {
                        vm.hasUserLevelPermission = (key === 'None' || !!(vm.userPermissions & vm.userLevelPermissionsEnum[key]));
                        return [key,value, vm.hasUserLevelPermission];
                    });

I appreciate the previous fix provided. The use of Object.keys() effectively tackled the problem.

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

redux saga: accessing different endpoint parameters

Recently, I encountered an endpoint function that looks like this: import AppConfig from "../config/app-config"; const create = (baseURL = AppConfig.apiUrl) => { const api = apisauce.create({ baseURL, headers: { "Cache-Control": "no-ca ...

Is there a way to ensure that a "loop once" animated GIF background will replay on each page refresh or load?

I currently have an animated GIF file set as the background image for my div, which was specifically configured in Photoshop to loop only once. Therefore, it only plays on the initial page load. Is there a way to reset the background image upon page refre ...

Delete the scene once the user has logged in successfully

Hey, I'm currently using Three.js for a pre-login homepage and I've wrapped the scene in a DIV. However, when the user clicks login and I try to hide/clear the screen, I'm running into issues with rendering. Even though I attempt to hide it, ...

Issue with JSON encoding in Embed message/interaction reply in Discord.js v14

I am currently utilizing Discord.js version 14.8, which was developed in typescript. Here is a snippet from my package.json file: "dependencies": { "@discordjs/rest": "^1.1.0", "@supabase/supabase-js": &quo ...

Having trouble getting Django to display images using jQuery? Uncaught Reference Error may be preventing it

Currently, I am experimenting with implementing a jquery example on my django-based website. As I am still in the learning phase, I kindly ask for your patience. This is a snippet of what my code looks like at this point: {% extends "base.html" %} {% loa ...

Exploring Angular 2 with Visual Studio 2015 Update 1 in the context of Type Script Configuration

After spending the last week attempting to set up and launch a simple project, I am using the following configuration: Angular 2, Visual Studio 2015 update 1, TypeScript Configuration In the root of my project, I have a tsconfig.Json file with the follow ...

The error message received is: `npm ERR! code ERR_TLS_CERT_ALTNAME_INVALID

Setting up a new Angular app after working on an existing one for months was quite challenging. Today, while trying to install the new Angular app through the terminal on my Mac, the process was unusually slow and ended up showing this error: npm ERR! co ...

Navigate to a different page using Angular with a simple click

How can I implement a redirect from clicking on the "Firms" word to another component page in Angular? I have tried using routerLink="/", [routerLink]="['/']". I have imported Routes in the app.module. I have also attempted this approach: import ...

When attempting to select dates from the picker options, the array is found to be devoid of any entries

My challenge lies in working with an array of dates retrieved from the server to determine which dates should be disabled on the datepicker. getStaffAvailability(){ let x = this; this.$http.get(this.weeklyAvailabilityUrl + "GetAv ...

Retrieving information from my JavaScript function

Recently, I encountered an issue with displaying data obtained through a request as it was showing up undefined. fetch(url) .then(res => res.json()) .then((manager) => { /* console.log(manager); */ for (i in manager.data){ var row = $( ...

What is the best way to convert the javascript code into clojurescript?

Looking to utilize capacitor/app in order to determine the state (background or active) of my iOS app. My project is built on Clojurescript, so I need to convert the following javascript code into a clojurescript equivalent. Javascript import { App } fro ...

When is it best to use an interface instead of defining an object directly in a function signature in Typescript?

When writing Typescript functions, what is considered the standard approach? For instance, which of the following three options is preferred: // Option 1 function myFunction (a: string) {} // Option 2 function myFunction ({ a }: { a: string }) {} // Opti ...

Increase the gap between the legend and the chart when utilizing charts.js

I'm currently working on a project using charts.js and running into a slight issue. The legend for my bar chart is overlapping with the values displayed. I've been attempting to troubleshoot this problem without much success so far, so I would g ...

Returning an incorrect array occurs when there is only one piece of data in the JSON

I successfully transferred JSON data from the server-side to the client-side. However, I encountered an issue with a function that is supposed to return the latest rate and currency_id. This function works for some products but not for others. When using ...

Facing an angular 502 error when attempting to use HttpParams in my code

I'm currently utilizing Angular 8 Utilizing HttpParams for Sending Data to the Server using the Post method Encountering a 502 status code error while sending data via HttpParams ERROR HttpErrorResponse {headers: HttpHeaders, status: 502, statu ...

Encountered a problem while trying to upload a file using node

Hi there! I seem to be facing an issue with the code snippet below. Every time I attempt to upload a file, the browser keeps loading indefinitely. Any thoughts on what might be causing this problem? app.js var formidable = require('formidable') ...

Looking to swap out innerHTML in a div multiple times with javascript?

When dealing with a div element that appears multiple times in your HTML: <div class="myclass">abc</div> <div class="myclass">abc def</div> ... How can I replace "abc" for all occurrences, rather than just the first one? (I' ...

Utilizing Ajax for submitting a form in Wordpress contact page

I am currently using Wordpress along with the Ninja Form plugin. I am trying to achieve a function where upon submitting a form, the data is posted to a service. <input type="submit" name="_ninja_forms_field_7" class="ninja-forms-field popup-submit" i ...

Balancing scrolling status in sibling components within React/Redux

Is it possible for a React component to control the scroll position of another sibling component? The main component, known as Parent, includes two child components: List (which contains a scrollable div) and Actions with a button that is meant to control ...

What is the process for making a referenced variable null?

My scenario is as follows: When a user clicks on a button in Phaser.io, I create a new Phaser.sprite and store it in a local variable called newSquare. This new sprite is then added to an array called Squares. At a later point, I call a function to destr ...