Is there anyway to implement XOR in javascript

前端 未结 18 579
孤城傲影
孤城傲影 2020-12-24 10:53

I\'m trying to implement XOR in javascript in the following way:

   // XOR validation
   if ((isEmptyString(firstStr) && !isEmptyString(secondStr)) |         


        
相关标签:
18条回答
  • 2020-12-24 11:50

    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).

    0 讨论(0)
  • 2020-12-24 11:55

    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

    0 讨论(0)
  • 2020-12-24 11:56

    I hope this will be the shortest and cleanest one

    function xor(x,y){return true==(x!==y);}
    

    This will work for any type

    0 讨论(0)
  • 2020-12-24 11:57

    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))) {
      // ...
    }
    
    0 讨论(0)
  • 2020-12-24 11:58

    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;
    }
    
    0 讨论(0)
  • 2020-12-24 11:58

    @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;
    }
    
    0 讨论(0)
提交回复
热议问题