In JavaScript, binary operations do not function well with options

Here is my situation... there are array items with binary options like

  • $item[0] = 0010
  • $item[1] = 1000
  • $item[2] = 0110
  • $item[3] = 1101

each bit represents an option

I want to compare these options with the customer's requested option, let's say it's 0010

So, I need a logic to display only $item[0] and $item[2] because the second byte is 1. However, when there is no customer option check: 0000, then I must show all items

Only when some options are displayed should there be a filter...

I wish I paid more attention in math class... I am lost now, please help!


Note: This code snippet is from here: http://jsfiddle.net/yHxue/ but I'm having trouble understanding this line:

markers[m].setMap(((markers[m].props & props)>>>0===props)? ((props)?map:null): null);
, so I tried rewriting it, but mine doesn't work!

Answer №1

If you're dealing with numeric data, simply apply the bitwise & operator to each element.

var customerOption = parseInt("0010", 2)

$item.forEach(function(n, i) {
    if (customerOption === 0 || ((n & customerOption) == customerOption))
        alert(i); // display this item
});

If your data consists of strings, then conversion to a number is necessary for each item.

Repeat the same process as above, but...

parseInt(n, 2);

var $item = [];
$item[0] = "0010"
$item[1] = "1000"
$item[2] = "0110"
$item[3] = "1101"

var customerOption = parseInt("0010", 2)

$item.forEach(function(n, i) {
    if (customerOption === 0 || ((parseInt(n, 2) & customerOption) == customerOption))
        document.querySelector("pre").textContent += "\n0010 matched index: " + i;
});

document.querySelector("pre").textContent += "\n\n"

var customerOption = parseInt("0110", 2)

$item.forEach(function(n, i) {
    if (customerOption === 0 || ((parseInt(n, 2) & customerOption) == customerOption))
        document.querySelector("pre").textContent += "\n0110 matched index: " + i;
});
<pre></pre>

Answer №2

Transform all the strings (both items and the mask) into numerical values using parseInt(string, 2).

If the value of mask is 0, simply include all the items. Otherwise:

Proceed to use the & operator to identify the shared 1 bits:

var common = item & mask;

Next, evaluate common:

  • If you require any of the masked bits, then non-zero value for common is sufficient.
  • If you need all the bits specified in the mask, then common should match with mask.

UPDATE:

markers[m].setMap(
  ((markers[m].props & props) >>> 0 === props) ?
  ((props) ? map : null) :
  null
);

markers[m].props & props identifies mutual 1 bits, as previously mentioned; >>> 0 ensures a positive number. This outcome is compared against props to confirm that all common bits align with those in props (similar to the second case mentioned earlier). If all bits from props are present, and if props isn't zero, then markers[m] is assigned to map; otherwise, it's set to null.

Answer №3

let choices = ['0010', '1000', '0110', '1111'];
const findMandatoryChoices = (userChoice) => {
    let userChoiceInt = parseInt(userChoice, 2);
    if (userChoiceInt) {
        return choices.filter((binarySequence) => {
            return parseInt(binarySequence, 2) & userChoiceInt;
        });
    } else {
        return choices;
    }
};

You should use it in this manner:

findMandatoryChoices('0010');

Answer №4

However, in the absence of customer options check : 0000 I must display all items

In twos complement, -1 is represented as all ones (1111) in binary

if (!props) props = -1;

When testing for a specific value in binary, use both bitwise AND (&) and strict equality (===)

needle === (needle & haystack)

For example, searching for needle = 1001 in haystack = 0001 will result in false, even though 1001 & 0001 evaluates to truthy 0001

In certain cases, it may not be advisable to rely on exact matches


You can create code that uses callbacks to process an array

function applyByFlag(flag, callbackTrue, callbackFalse) {
    if (!flag)
        flag = -1;
    function nop() {}
    if (!callbackTrue) callbackTrue = nop;
    if (!callbackFalse) callbackFalse = nop;
    boxes.forEach(function (e, i, a) {
        if (flag & e) // non-exact test
            callbackTrue.call(e, e, i, a);
        else
            callbackFalse.call(e, e, i, a);
    });
}

It's recommended to modify the test to work with e.props

Answer №5

Your code is almost complete; just remember to include an extra check for when the props value is zero:

for(var m=0; m < markers.length; m++) {
    var show = (markers[m].props & props)>>>0===props || props == 0;
    markers[m].setMap(show ? map : null);
}

Check out the demo here!

The expression markers[m].props & props will result in either a 0 (if not all bits of props match) or the actual value of props (if all bits match).

The added ">>>0" will convert the expression into an unsigned 32-bit integer value, though it's optional if you use this revised expression instead:

var show = (markers[m].props & props) || props == 0;

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

Step-by-step guide on utilizing a for loop to print out each element of an array on the console

Currently, I am tackling an assignment that delves into experimenting with various loop types. In particular, I am tasked with using a for loop to output each item in the array named 'cars' utilizing console.log. It's essential to note that ...

Using jQuery to add a class after a specified delay

I am looking to enhance my menu options by continuously adding and removing the "current" class for each <li> item. Here is an example of my basic menu: <ul> <li>item 1</li> <li>item2</li> </ul> How can I ...

Steps to make background color transparent in Phaser 3

Issue I encountered a problem when adding two Text objects to a scene. The background color of the latter one could not be set to transparent. Is there anyone who can assist me with this? Below is a screenshot for reference. Attempted Solutions I at ...

How can ternary conditional operators be transformed into if statements?

When dealing with minified code like this, f&&!f.error?k.button.b==k.button.c.G?k.button.Q(b,e,f,c,d):k.button.b==k.button.c.o&&k.button.P(b,e,f,c,d):(console.error(f),f=f.error.message||chrome.i18n.getMessage("error_tooltip"),k.button.v(b ...

Guide to invoking an API in Next.js 13 by utilizing specific variables within a client component

I currently have a collection of products that are accessible on my website through a straightforward function within a server component. async function getData() { const res = await fetch(`${apiPath}`); const data = (await res.json()) as PackProps ...

There appears to be an issue with the functionality of the JavaScript calculation function

Check out this JS Fiddle. I've tried my best in writing the script, but it just doesn't seem to work properly. If you could spare some time to review it and provide feedback on what I might be missing or doing wrong, I would greatly appreciate it ...

Append a sequence of eight characters following a specific character in a CharArray to create a new String

Here is the string I am working with: }1311202013112020607169018}1611202016112020}1411202014112020626948615}1511202015112020}1811202018112020 To break it down, it looks like this: }13112020 13112020607169018 }16112020 16112020 }14112020 14112020626948615 ...

Is it possible to apply (max / min) to a mongoose string?

Is it possible to limit the maximum string length to 5 characters using this method? Or is this functionality only available for numbers? someString: { type: String, max: 5 }, Thank you! ...

Encountering TypeScript error TS2345 while attempting to reject a Promise with an error

I recently encountered a perplexing TypeScript error message that I am struggling to comprehend. The specific error reads as follows: error TS2345: Argument of type '(error: Error) => void | Promise' is not assignable to parameter of type & ...

Organizing a two-dimensional array

I am struggling to organize two sets of data, whether they are in a 2d array or parallel arrays. I can't seem to crack it. Here are the two datasets: /////method one/// int id[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int numDetected[10] = {40, 21, 2, ...

Trigger function when an option is chosen from the jQuery UI autocomplete suggestion list

Hello, I have implemented an autocomplete feature in my code which is functioning properly. However, I am facing an issue where the desired function (doSomething()) is not triggered when a user clicks on an option from the autocomplete list. The function o ...

Having trouble with V-For image paths not locating the image files? Need help on adding the right file path while using v-for?

I am currently using Vue/Nuxt and facing an issue with populating an image carousel. The images I want to insert into the carousel are stored in a folder named "AreaPictures" within my assets directory. This is how my v-for loop is structured: &l ...

Challenges encountered with the login page within the script document

I am struggling to make this simple code work. Here is the code snippet I am working with that needs to list two user names along with their selected passwords. While I understand hardcoding in the script is not ideal, it is required for this assignment. ...

Add the necessary js, html, and css files to enhance an angular project

Looking for assistance with integrating a Javascript project within an Angular project. Is it possible to integrate JavaScript files into an Angular project? If so, how can I place the JS files into the assets folder? And where should we include the HTML ...

I am unable to close the hamburger menu by clicking on it

I am facing an issue with the hamburger icon functionality. The menu opens when I click on it, but it is not getting closed when clicked again. I have been trying to debug the code, but I can't figure out what's causing the problem. If anyone has ...

struggling to get react-router working with reactjs

I've been working on setting up a simple reactjs SPA with nodejs, but I'm encountering issues with my Router not functioning correctly. I started a new App using create-react-app and installed react-router using npm install. Here is my package.js ...

Error displaying component with react-router v5 not found

Currently, I am immersed in developing interactive dashboard web applications using ReactJS. I am utilizing React Routing to seamlessly navigate through the website's content. Here is a snapshot of my web application: https://i.sstatic.net/Ye8bH.png ...

Ways to retrieve an object from a separate function in JavaScript

I am struggling to fetch data from an array and store it in an object. However, every time I try, I end up with either an empty object or a Promise { <pending> } shown in the logs. I have attempted to use a global variable to store the data and acc ...

How can I make my navbar stay fixed in place and also activate the transform scale functionality?

After fixing the position of my navbar with the class "top," I noticed that the transform property scale does not work on the div element I applied. The hover effect on the box only works when I remove the position from the navbar. This is the HTML code: ...

Top solution for efficiently capturing and storing user input in a React JS application: Event Handler

I've recently designed an input field for inputting details of items. In order to effectively capture and save the entered information, which of the following event handlers would be most suitable? onClick onChange onLoad onKeyPress ...