Sunday, May 9, 2021

Javascript Practice 40: JS Hero - XOR

 
Question: 

Write a function xor that takes two Boolean values. If both values are different, the result should be true. If both values are the same, the result should be false.

I.e.: The calls xor(true, false) and xor(false, true) should return true. The calls xor(true, true) and xor(false, false) should return false.




Answer: 

function xor (boo1, boo2) {

let xor = (boo1 || boo2) && (!boo1 || !boo2);

return xor; 

}; 

> in this post, I will code a XOR Gate (eXclusive OR)
> we declare a variable 'xor' 
> we initialize it with a value of both our Boolean parameters
> like this (boo1 || boo2) && (!boo2 || !boo1);
> so if boo1 & boo2 are both true (or both are false) then variable 'xor' will store the value false and in all other cases it will store the value of true
>> xor(true, true) = false >>>> (true || true) && (false || false) >>>> check in console
>> xor(false, false) = false >>>> (false || false) && (true || true) >>>> check in console
>> xor(true, false) = true >>>> (true || false) && (false || true) >>>> check in console
>> xor(false, true) = true >>>> (false || true) && (true || false) >>>> check in console

No comments:

Post a Comment