Reputation: 9696
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.
Upvotes: 3
Views: 4637
Reputation: 5885
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;
}
Upvotes: 0
Reputation: 26312
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
Upvotes: 0
Reputation: 145408
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.
Upvotes: 8
Reputation: 74204
What you're looking for is the xor operator:
1 ^ 1 = 0;
1 ^ 0 = 1;
1 ^ 1 ^ 1 = 1;
Upvotes: 2