Is there anyway to implement XOR in javascript

前端 未结 18 765
孤城傲影
孤城傲影 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:44

    Here is an XOR function that takes a variable number of arguments (including two). The arguments only need to be truthy or falsy, not true or false.

    function xor() {
        for (var i=arguments.length-1, trueCount=0; i>=0; --i)
            if (arguments[i])
                ++trueCount;
        return trueCount & 1;
    }
    

    On Chrome on my 2007 MacBook, it runs in 14 ns for three arguments. Oddly, this slightly different version takes 2935 ns for three arguments:

    function xorSlow() {
        for (var i=arguments.length-1, result=false; i>=0; --i)
            if (arguments[i])
                result ^= true;
        return result;
    }
    

提交回复
热议问题