Reputation: 85
The cord I am in need is below:
//These two variables are double and both can be 0.0, so the result can be NaN.
(data['amount'] / totalSpending).isNaN ? 0.0 : (data['amount'] / totalSpending)
The equivalent can be achieved in Javascript, like this
data['amount'] / totalSpending || 0.0
I want to do same thing in Dart, but the ||
operator doesn't seem to allow other than type boolean in Dart. Do you have any solution for this?
Upvotes: 0
Views: 91
Reputation: 90135
There's no built-in way, but you could do:
extension DefaultNaN on double {
double defaultIfNaN(double value) => isNaN ? value : this;
}
and then you could do (data['amount'] / totalSpending).defaultIfNaN(0)
.
You can't override ||
since ||
has special short-circuiting behavior, but you alternatively could override |
for double
:
extension DefaultNaN on double {
double operator |(double value) => isNaN ? value : this;
}
and then you could do data['amount'] / totalSpending | 0
. However, I don't necessarily recommend that since I personally don't think that (or even JavaScript's ||
usage) is very readable, and if someone reading the code isn't already familiar with it, it's hard to search for.
Upvotes: 2