Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing xnor in javascript

Tags:

javascript

I have two strings stored in a & b. I want to perfrom some validation if both strings have some value. For this I use:

if(a && b) {
    //Do some processing.
}

However if one of them is empty and the other is not, then I need to treat it separately. If both are empty, I don't need to do anything. So basically to handle this case it is the false case of XNOR. I could do this way:

if((a && !b) || (!a && b)) {
    //handle separately. 
}

Is there a better approach than this?

like image 474
user1692342 Avatar asked Dec 19 '17 18:12

user1692342


2 Answers

JavaScript does not have XOR and XNOR operators. There are many ways to implement them, and the way you implemented it is fine. Another way can be by using the ternary operator:

//XOR
if( a ? !b : b ) {
  ...
}

//XNOR
if( a ? b : !b ) {
  ...
}

However, all those methods have a downside of potentially evaluating a and b more than once. That can be a problem if a or b is a function or expression. A better approach can be by rewording the definition of XOR to: return true if the two boolean operands do not have the same value. We can implement that like this:

//XOR
if( a != b ) {
  ...
}

//XNOR
if( a == b ) {
  ...
}

Now, this is much shorter and, more importantly, only evaluates a and b once. However, this only works if both a and b are booleans. If you want to support other types, you'll have to convert them to booleans first:

//XOR
if( !a != !b ) {
  ...
}

//XNOR
if( !a == !b ) {
  ...
}
like image 88
Racil Hilan Avatar answered Nov 12 '22 22:11

Racil Hilan


Let's combine your two separate if-statements into one (effectively the same, but will help with the simplification):

if (a && b)
    // do some processing
else if (a && !b || !a && b)
    // do other processing

To figure out if we can simplify further, let's look at the truth table for the second condition:

a  |  b  |  x
--------------
1  |  0  |  1  (a && !b)
0  |  1  |  1  (!a && b)
0  |  0  |  0  (a && b) (negating the first if)

You can see that the positive outcomes (x = 1) are present when a is true or when b is true, which simplifies to a || b. The final version of your if-statement would look like:

if (a && b)
    // do some processing
else if (a || b)
    // do other processing
like image 39
Cᴏʀʏ Avatar answered Nov 12 '22 21:11

Cᴏʀʏ