Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Related to my original question, how would you xor three boolean variables in javascript. One variable can be true the rest must be false.

This is my solution, but I feel there is a better one:

function isValid(a, b, c) {
  return (a !== b ! == c) && [a, b, c].includes(false);
}

I've gotten some feed back from the comments, let me define what I'm asking (sorry for all the confusion).

  1. I'm actually doing this in a typescript class. I figured I'd just remove the method and make it a classless function. I realize now that this does affect the solution. Sorry about that.

  2. I suppose I must have missused the term XOR. What I'm trying to say is, only a OR b OR c can be true, and one of them must be true. I hope that is more clear.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
144 views
Welcome To Ask or Share your Answers For Others

1 Answer

If these are boolean values, just filter and test that only one is true:

function isValid(...args) {
  return args.filter(v => v).length == 1;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...