Exploring the retrieval of specific values through bitwise operations in Angular

Currently, I am facing a challenge in retrieving a value that I had initially saved in the database as a sum of bits. My development work is based on Angular 9 using Typescript.

I have successfully managed to store the sum of bits in the database. Now, I need to display these values on another screen by fetching them from the database.

Assuming that in my .ts file, I have an array of strings:

bitwiseLabels: string[] =
    ['Kitchen', 'Bedroom', 'Living Room'];

From the database, I retrieve the number 3, which represents the sum of 1 and 2. As a result, I want to display 'Kitchen' and 'Bedroom' on the screen respectively.

Unfortunately, I haven't been able to find a working solution so far. Any advice or suggestions would be greatly appreciated.

Answer №1

To retrieve the initial values, you can utilize bit masks:

const getItems = (elements, select) =>
    elements.filter((_, index) => select & (1 << index));

const bitwiseOptions = ['option A', 'option B', 'option C'];

   
    
console.log(getItems(bitwiseOptions, 3));

console.log(getItems(bitwiseOptions, 4));

console.log(getItems(bitwiseOptions, 5));

console.log(getItems(bitwiseOptions, 6));

console.log(getItems(bitwiseOptions, 7));

If you wish to extract individual numerical values, the following approach can be taken:

const getItems = (elements, select) =>
    elements.map((_, index) => 1 << index).filter((i) => select & i);

const bitwiseOptions = ['option A', 'option B', 'option C'];

   
    
console.log(getItems(bitwiseOptions, 3));

console.log(getItems(bitwiseOptions, 4));

console.log(getItems(bitwiseOptions, 5));

console.log(getItems(bitwiseOptions, 6));

console.log(getItems(bitwiseOptions, 7));

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

Angular 14: Trouble with ngFor after latest update - Type 'unknown' causing issues

Just updated my project to angular version 14.0.4 Within the html of a component, I have the following code: <div class="file" *ngFor="let file of localDocumentData.files; index as i;"> <div class="card"> ...

Challenges with date formatting arise for Spanish speakers when the date returns as NaN or an Invalid

I have been working on an Angular app Objective: My aim is to allow users to input dates in Spanish format (DD/MM/YYYY) and display them as such, while converting them back to English format when saving the data to the Database. Issue: One problem I enco ...

Effectively managing user access by authorizing levels and securing routes

Below is the code snippet for a protected route where the authentication status is managed by Redux. If there is no token saved in local storage, the isAuthenticated state is set to false. This code snippet is for protecting routes: import PropTypes from & ...

Transforming encoded information into a text format and then reversing the process

I am facing an issue with storing encrypted data in a string format. I have tried using the TextEncoder method but it seems to be creating strings with different bytes compared to the original ArrayBuffer. Here is the line causing the problem: const str ...

415 Media Type Not Supported - Please choose a different format

While working with the backend, I have encountered an issue where the 'DELETE' method is returning a 415 unsupported media type error. After conducting research, it seems that the cause of this error may be due to the content-type header not bein ...

How can I utilize Angular and TypeScript to loop through the innerHTML property binding effectively?

I'm currently working on using ngFor to display the binding details of the innerHtml property. <ul> <li *ngFor="let n of NotificationData"> {{n.NotificationID}} <label [innerHtml]="n.NotificationText | StyleHtml&quo ...

Module 'next-intl/client' cannot be located

When I run npm test, I encounter the following error: 'next-intl/client' module not found jest.mock( | ^ 22 | 'next-intl/client', 23 | (): Record<string, unknown> => ({ 24 | usePathname: ...

Using Firebase with Angular 4 to fetch data from the database and show it in the browser

Currently diving into Angular 4 and utilizing Firebase database, but feeling a bit lost on how to showcase objects on my application's browser. I'm looking to extract user data and present it beautifully for the end-user. import { Component, OnI ...

Angular allows you to pass an array of objects as FormData items

Is there a way to send FormData with an array of objects to an API? I have attempted the following: https://i.stack.imgur.com/BlYby.png This is the request payload. How can I retrieve all items with other data from my .NET Core C# API? public class Back ...

What causes the Angular child component (navbar) to no longer refresh the view after a route change?

Hello everyone, I'm excited to ask my first question here. Currently, I am working on developing a social network using the MEAN stack and socket.io. One of the challenges I am facing is displaying the number of unread notifications and messages next ...

Converting an array with objects to comma separated strings in javascript using (ionic , Angular , NodeJS , MongoDB)

Retrieving specific data from an API array: let passions = [ {_id: "60a1557f0b4f226732c4597c",name: "Netflix"}, {_id: "60a1557f0b4f226732c4597b",name: "Movies"} ] The desired output should be: ['60a1557f0b4f226 ...

Error in Typescript: Cannot assign type 'string[]' to type 'string'

I'm currently developing a project using Next.js with Typescript and .tsx files, and I'm utilizing Supabase as my database. While everything is functioning perfectly on localhost, I'm encountering an issue when trying to build the project o ...

Tips for refreshing a component after fetching a new page using the useQuery function

Attempting to retrieve and display data from my custom API using axios and react-query's useQuery. The API incorporates pagination, and I have implemented a table with an option to select the page that displays the current data. Everything functions c ...

The code encountered an error when trying to access the property 'template' of an undefined variable in the MatRowDef.push

I am encountering an issue with Angular lazy loading. Whenever I switch from one child component to another, I receive an error in a component where I have implemented a mat-table for displaying data. Error: TypeError: Cannot read property 'template& ...

Angular application that features a material table created using *ngFor directive and displayedColumns defined as an array

I am trying to create a table that displays columns with the format {key: string, display: string} where 'display' is the header and 'key' is used to display the value. <ng-container *ngFor="let col of displayedColumns"> ...

Highcharts3d was already defined locally, preventing the import declaration from being recognized with error code TS2440

Struggling to get my application to run in VS code due to this persistent error: error TS2440: Import declaration conflicts with local declaration of 'Highcharts3d' Any assistance in resolving this issue would be greatly appreciated. import ...

What is the reason buttons in mat-menus do not submit?

I have implemented a mat-menu to showcase a list of choices for the user. The objective is to trigger the submission of my formGroup when a user selects an option from the menu. dropdown.component.html <form [formGroup]="myForm" (ngSubmit)=onSubmit(my ...

Using Svelte with Vite: Unable to import the Writable<T> interface for writable store in TypeScript

Within a Svelte project that was scaffolded using Vite, I am attempting to create a Svelte store in Typescript. However, I am encountering difficulties when trying to import the Writable<T> interface as shown in the code snippet below: import { Writa ...

The custom FontAwesome icon is failing to display properly

UPDATE : Here is the StackBlitz as requested. A custom SVG icon was created based on instructions provided by FontAwesome's collaborator found here. Despite mirroring the exact element structure of FontAwesome's icons, the custom icon does not ...

A common method for incorporating personalized react-scripts into create-react-app

After creating a project using create-react-app in TypeScript, I am looking to integrate custom react-scripts without ejecting. What is the most effective approach to achieve this? ...