I want to validate an object that has three Boolean properties, of which one, and only one, must be true. What is the best way to check this?
I came up with this:
var t1 = obj.isFirst ? 1 : 0, t2 = obj.isSecond ? 1 : 0, t3 = obj.isThird ? 1 : 0; var valid = (t1 + t2 + t3) === 1; This works fine, but it feels a bit like a hobbyists solution :-)
Is there a better way of doing this? Using XOR (^) for example?
obj.isFirst + obj.isSecond + obj.isThird === 1, assuming it is certain they are booleans and not something different. You can add explicit conversion if you like (e.g.Number(obj.isFirst)), but javascript also implicitly converts.obj.position = (1|2|3)