Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Created May 5, 2020 18:17
Show Gist options
  • Save dfkaye/5135495dd260cba71076cb8a8174f2ad to your computer and use it in GitHub Desktop.
Save dfkaye/5135495dd260cba71076cb8a8174f2ad to your computer and use it in GitHub Desktop.
XOR function in JavaScript
// 5 May 2020
// XOR - because I keep forgetting what it means ("exclusive OR").
// It compares 2 primitive values and returns true if only one is true,
// otherwise returns false.
// Could be more robust (reject Object comparisons, e.g.).
function XOR(a, b) {
return !a !== !b
}
/* test it out */
var tests = [
[1, 0],
[true, false],
[0, 0],
[1, -1]
].map(function(pair) {
return XOR.apply(0, pair);
});
console.log(JSON.stringify(tests, null, 2));
/*
[
true,
true,
false,
false
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment