Skip to content

Commit

Permalink
fix: add exception to per100gInUnit and perServingInUnit in ProductNu…
Browse files Browse the repository at this point in the history
…triment

Closes OPENFOODFACTS-ANDROID-491
Closes #4185
  • Loading branch information
VaiTon committed Aug 25, 2021
1 parent 42c8c35 commit 783ba34
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
Expand Up @@ -106,6 +106,8 @@ class ProductNutriments : Serializable {
) {
val unit = unit.getRealUnit()

fun isEnergy() = unit in ENERGY_UNITS

fun getPer100gDisplayString() = buildString {
modifier.ifNotDefault {
append(it.sym)
Expand All @@ -118,15 +120,23 @@ class ProductNutriments : Serializable {
* Returns the amount of nutriment per 100g
* of product in the units stored in [ProductNutriment.unit]
*/
val per100gInUnit get() = per100gInG.convertTo(unit)
val per100gInUnit: Measurement
get() {
return if (isEnergy()) per100gInG
else per100gInG.convertTo(unit)
}

/**
* Returns the amount of nutriment per serving
* of product in the units stored in [ProductNutriment.unit].
*
* Can be null if [perServingInG] is null.
*/
val perServingInUnit get() = perServingInG?.convertTo(unit)
val perServingInUnit: Measurement?
get() {
return if (isEnergy()) perServingInG
else perServingInG?.convertTo(unit)
}

/**
* Calculates the nutriment value for a given amount of this product. For example,
Expand Down
Expand Up @@ -53,6 +53,7 @@ fun Measurement.convertTo(unit: MeasurementUnit): Measurement {
when (unit) {
ENERGY_KJ, ENERGY_KCAL ->
throw IllegalArgumentException("Cannot convert from/to energy. Use convertEnergyTo instead.")

UNIT_DV, UNIT_IU ->
throw IllegalArgumentException("Cannot convert to DV or IU")

Expand Down

0 comments on commit 783ba34

Please sign in to comment.