Skip to content

Commit

Permalink
feat: 648 - new method "Nutriments.isEmpty" (#649)
Browse files Browse the repository at this point in the history
Impacted files:
* `api_getProduct_test.dart`: added tests around new method `Nutriments.isEmpty`
* `Nutriments.dart`: new method `isEmpty`; added comments
  • Loading branch information
monsieurtanuki authored Dec 25, 2022
1 parent 44dfd2d commit d04e9eb
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
22 changes: 22 additions & 0 deletions lib/model/Nutriments.dart
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ class Nutriments extends JsonObject {
/// between totally unknown values and values that have been erased.
final Map<String, double?> _map = <String, double?>{};

/// Returns the map key for that [nutrient] and that [perSize].
String _getTag(
final Nutrient nutrient,
final PerSize perSize,
Expand All @@ -64,10 +65,31 @@ class Nutriments extends JsonObject {
return this;
}

/// Returns true if there are no populated nutrients at all.
///
/// Default case: a nutrient with a null value is considered "populated".
/// If [isNullEmpty] is true, a null value is a non populated value, and a
/// [Nutriments] with only null values would be considered empty.
bool isEmpty({final bool isNullEmpty = false}) {
if (_map.isEmpty) {
return true;
}
if (!isNullEmpty) {
return false;
}
for (final double? value in _map.values) {
if (value != null) {
return false;
}
}
return true;
}

/// Returns the default [Unit] of that [nutrient].
@Deprecated('Use nutrient.typicalUnit instead')
Unit? getUnit(final Nutrient nutrient) => nutrient.typicalUnit;

/// Returns the energy in kJ for that [perSize], direct or computed from kcal.
double? getComputedKJ(final PerSize perSize) {
double? result;
result = getValue(Nutrient.energyKJ, perSize);
Expand Down
18 changes: 18 additions & 0 deletions test/api_getProduct_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2114,5 +2114,23 @@ void main() {
expect(result.product!.noNutritionData, isFalse);
expect(result.product!.nutriments, isNotNull);
});

test('Empty nutriments', () async {
final Nutriments nutriments = Nutriments.empty();

expect(nutriments.isEmpty(), isTrue);
expect(nutriments.isEmpty(isNullEmpty: true), isTrue);
expect(nutriments.isEmpty(isNullEmpty: false), isTrue);

nutriments.setValue(Nutrient.calcium, PerSize.oneHundredGrams, 12);
expect(nutriments.isEmpty(), isFalse);
expect(nutriments.isEmpty(isNullEmpty: true), isFalse);
expect(nutriments.isEmpty(isNullEmpty: false), isFalse);

nutriments.setValue(Nutrient.calcium, PerSize.oneHundredGrams, null);
expect(nutriments.isEmpty(), isFalse);
expect(nutriments.isEmpty(isNullEmpty: true), isTrue);
expect(nutriments.isEmpty(isNullEmpty: false), isFalse);
});
}, timeout: Timeout(Duration(seconds: 90)));
}

0 comments on commit d04e9eb

Please sign in to comment.