Question

How do i do a clean boolean add in javascript?

1+1 = 0;
1+0 = 1;
1+1+1 = 1;

etc. can one just sum booleans?

true+true = false
false+true = true;

etc.

Was it helpful?

Solution

Just use bitwise XOR operator:

1 ^ 1 = 0
1 ^ 0 = 1
1 ^ 1 ^ 1 = 1

FWIW: The same works for most high-level programming languages.

OTHER TIPS

What you're looking for is the xor operator:

1 ^ 1 = 0;
1 ^ 0 = 1;
1 ^ 1 ^ 1 = 1;
1 ^ 1 = 0;
1 ^ 0 = 1;

for boolean this can be achieved by using Short-circuit AND and OR operators.

function myXOR(a,b) {   
       return ( a || b ) && !( a && b );    
}
myXOR(true,true) == false

you can code yor for bool like this:

function xor(a,b) {
  if (a === true && b === true) {
     return false;
   }
 return a || b;   
}

OR in typescript:

   xor(a: boolean,b: boolean): boolean {
     if (a === true && b === true) {
       return false;
     }
     return a || b;
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top