I'm trying to understand how does this piece of code work. I know that the ternary operator is condition ? option1 : option2 but I don't know how does this work in this scenario.
constructor(minSupport: number, minConfidence: number, debugMode: boolean) {
this.minSupport = minSupport ? minSupport === 0 ? 0 : minSupport : 0.15;
this.minConfidence = minConfidence ? minConfidence === 0 ? 0 : minConfidence : 0.6;
this.debugMode = debugMode || false;
}
This:
this.minSupport = minSupport ? minSupport === 0 ? 0 : minSupport : 0.15;
translates into:
if (minSupport) {
if (minSupport === 0) {
this.minSupport = 0;
} else {
this.minSupport = minSupport;
}
} else {
this.minSupport = 0.15;
}
Given this example the others should be easy to work out. Personally I don't like nested ternary expressions like you've posted. A nice if/then statement is much simpler to work out the flow of logic.
This is a case study on why writing code as tersely as possible does not make it better.
Shoving everything into a single line makes it hard to read and comprehend the flow. I find that adding a little bit of formatting makes things much more legible:
this.minSupport =
minSupport
? minSupport === 0
? 0
: minSupport
: 0.15;
There are a variety of ways to format that code to make it easier to digest. At this point we can walk through the logic:
if minSupport is truthy:
check if minSupport is zero (literally can't happen because 0 is not truthy). If it is (it can't be) set this.minSupport to 0. Otherwise, set this.minSupport to whatever value minSupport contained.
else if minSupport is falsey:
set this.minSupport to 0.15
So with that logic digested, it's clear that there's a secondary check that intends to preserve the value of 0. The code is buggy, and the fix is to change the logic:
this.minSupport =
minSupport
? minSupport
: minSupport === 0
? minSupport
: 0.15;
now with that reflow, we can look over the logic and see that it can be condensed. We want to set this.minSupport to minSupport if minSupport is truthy or if minSupport is 0.
The simplification looks like:
this.minSupport =
minSupport || minSupport === 0
? minSupport
: 0.15;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With