This JavaScript condition is very strange...
I was writing this code...
class Fraction {
// snip
toString() {
if (this.numerator === 0)
return "0";
let result = "";
if (this.constructor.SYMBOL)
if (this.numerator === -1)
result += "-";
else
result += this.numerator;
result += this.constructor.SYMBOL;
if (this.denominator !== 1)
result += "/" + this.denominator;
return result;
}
}
class PiFraction extends Fraction {
static SYMBOL = "π";
}
but I quickly saw that it was doing the wrong thing, e.g.
» new PiFraction(1, 4).toString()
← "1π/4"
which is not a fully simplified fraction.
I ended up finding the error, which was:
class Fraction {
toString() {
// snip
if (this.constructor.SYMBOL) {
if (this.numerator === -1) {
result += "-";
}
} else {
result += this.numerator;
}
// snip
}
}
which was what I meant when indenting the code, but the JavaScript compiler didn't understand it and compiled the nested conditional first.
So if you write this:
if (a)
if (b)
c();
else
d();
Be careful, because it gets evaluated as:
if (a) {
if (b) {
c();
}
else {
d();
}}
and NOT as:
if (a) {
if (b) {
c();
}
} else {
d();
}
as you would expect it.
The last code snippet is the only one that you should use.