I\'m trying to implement XOR in javascript in the following way:
// XOR validation
if ((isEmptyString(firstStr) && !isEmptyString(secondStr)) |
XOR just means "are these two boolean values different?". Therefore:
if (!!isEmptyString(firstStr) != !!isEmptyString(secondStr)) {
// ...
}
The !!
s are just to guarantee that the !=
operator compares two genuine boolean values, since conceivably isEmptyString()
returns something else (like null
for false, or the string itself for true).
Javascript does not have a logical XOR operator, so your construct seems plausible. Had it been numbers then you could have used ^ i.e. bitwise XOR operator.
cheers
I hope this will be the shortest and cleanest one
function xor(x,y){return true==(x!==y);}
This will work for any type
You could use the bitwise XOR operator (^
) directly:
if (isEmptyString(firstStr) ^ isEmptyString(secondStr)) {
// ...
}
It will work for your example since the boolean true
and false
values are converted into 1
and 0
because the bitwise operators work with 32-bit integers.
That expression will return also either 0
or 1
, and that value will be coerced back to Boolean by the if
statement.
You should be aware of the type coercion that occurs with the above approach, if you are looking for good performance, I wouldn't recommend you to work with the bitwise operators, you could also make a simple function to do it using only Boolean logical operators:
function xor(x, y) {
return (x || y) && !(x && y);
}
if (xor(isEmptyString(firstStr), isEmptyString(secondStr))) {
// ...
}
here's an XOR that can accommodate from two to many arguments
function XOR() {
for (var i = 1; i < arguments.length; i++)
if ( arguments[0] != arguments[i] )
return false;
return true;
}
Example of use:
if ( XOR( isEmptyString(firstStr), isEmptyString(secondStr) ) ) {
alert(SOME_VALIDATION_MSG);
return;
}
@george, I like your function for its capability to take in more than 2 operands. I have a slight improvement to make it return faster:
function xor() {
for (var i=arguments.length-1, trueCount=0; i>=0; --i)
if (arguments[i]) {
if (trueCount)
return false
++trueCount;
}
return trueCount & 1;
}