Reputation: 23
I got this out of an exam question, and couldn't understand how the solution works. This function is supposed to return "true" if the values "x" and "y" are equal, and return False otherwise.
The solution:
function equal_boolean (x , y) {
return x ? y : y ? x : true;
}
Why does this work? As much as I can understand, it would turn out to be evaluating if X is true. If X is true, it would return Y. How is X supposed to be "true"?
If it isn't, it would evaluate whether Y is true, if it's true it would return X, and if it isn't - it would return True.
Is there something wrong with my understanding?
Upvotes: 2
Views: 770
Reputation: 74705
The first thing you should do is group the ternary operators together:
(x ? y : (y ? x : true))
x
is true
, then return y
, whose value also tells you whether x
and y
are equalx
is false
, then start with the second ternary:
y
is true
, then return x
(false
) as the two are not equaly
is false
, then x
and y
are equal, so return true
Upvotes: 3
Reputation: 215059
return x ? y : y ? x : true;
parses as
if x
return y // if y is true, then x == y. if y is false, then x != y
else (x is false)
if y
return x // x is false and y is true, y != x, return false
else
return true // x is false and y is false, return true
This is of course a pretty convoluted way to express boolean equality (aka Logical biconditional aka iff
). More natural would be an expression like this:
(x && y) || (!x && !y)
Upvotes: 4
Reputation: 4339
First identify the expressions
return x ? y : y ? x : true;
//turns into
return x ? y : (y ? x : true);
Replace the ?:
ternary operators by if
statements
if (x) {
return y;
} else {
//here x is false, so we will be able to replace x by false in the next step
if (y) {
return x;
} else {
return true;
}
}
Make if
statements more verbose, replace return x
by return false
if (x == true) {
return y;
} else {
if (y == true) {
return false;
} else {
return true;
}
}
Finally replace return y;
by if (y == true) { return true; } else { return false; }
, and check all the possibilities
if (x == true) {
if (y == true) {
return true; // x == true and y == true
} else {
return false; // x == true and y == false
}
} else {
if (y == true) {
return false; // x == false and y == true
} else {
return true; // x == false and y == false
}
}
It works. (As long as x and y are booleans)
Upvotes: 0
Reputation: 2235
Let's try expanding this a bit:
var myBool = x ? y : (y ? x : true)
return myBool;
First block
x ? y : ...
if X is true, then return value of Y. If Y happens to be true, both are equal. Otherwise return false (no match).
Second block if X was false:
y ? x : true
if Y is true, return X. X was false, so false is returned (no match) if Y is false, return true - both values are false.
Upvotes: 0