getLargestUnit method
Determines the largest unit that has a value of at least 1
.
This method will determine which unit within permissibleUnits
is the largest unit that has a value of at least
1
. This is typically useful to determine which unit should be used to visualize a unit of measurement.
Implementation
TUnit getLargestUnit({
required Set<TUnit> permissibleUnits,
}) {
if (permissibleUnits.isEmpty) {
throw ArgumentError('permissibleUnits cannot be empty');
}
TUnit? largestUnit;
Rational? largestUnits;
TUnit? smallestUnit;
Rational? smallestUnits;
for (final unit in permissibleUnits) {
final units = getUnits(unit);
// Logic is counterintuitive. If the number of units for a given unit is less than the current largest units,
// and is more than one, that means we have at least one of those units and it is larger than the currently
// selected unit because there are fewer of them.
if (units >= Rationals.one &&
(largestUnits == null || units < largestUnits)) {
largestUnit = unit;
largestUnits = units;
}
if (smallestUnits == null || units > smallestUnits) {
smallestUnit = unit;
smallestUnits = units;
}
}
if (largestUnit != null) {
return largestUnit;
} else {
// None of the units has at least a value of 1, so return the smallest unit instead.
return smallestUnit!;
}
}