Explorar o código

Shortcut unit conversions.

A zero measurement is zero in any other unit.
Thomas Flucke %!s(int64=2) %!d(string=hai) anos
pai
achega
d87e911eb8

+ 25 - 23
shared/shared/src/main/scala/com/weEat/shared/models/MeasureUnit.scala

@@ -27,29 +27,31 @@ sealed trait MeasureUnit {
     food: FoodNode,
     amount: Double,
     to: MeasureUnit
-  ): Try[Double] = ((typ, to.typ) match {
-    case (fTyp, tTyp) if fTyp == tTyp => Success(amount * to.conversionRatio)
-    case (MASS, VOLUME) => food.density match {
-      case Some(density) => VOLUME.defaultUnit
-          .convert(food, amount / density, to)
-      case None => Failure(new IncompleteDataException(food, "density"))
-    }
-    case (MASS, NUMBER) => food.massPerUnit match {
-      case Some(massPerUnit) => NUMBER.defaultUnit
-          .convert(food, amount / massPerUnit, to)
-      case None => Failure(new IncompleteDataException(food, "mass/unit"))
-    }
-    case (VOLUME, _) => food.density match {
-      case Some(density) => MASS.defaultUnit
-          .convert(food, amount * density, to)
-      case None => Failure(new IncompleteDataException(food, "density"))
-    }
-    case (NUMBER, _) => food.massPerUnit match {
-      case Some(massPerUnit) => MASS.defaultUnit.
-          convert(food, amount * massPerUnit, to)
-      case None => Failure(new IncompleteDataException(food, "mass/unit"))
-    }
-  }).map(_ * conversionRatio)
+  ): Try[Double] = if (amount == 0.0) Success(0.0)
+  else
+    ((typ, to.typ) match {
+      case (fTyp, tTyp) if fTyp == tTyp => Success(amount * to.conversionRatio)
+      case (MASS, VOLUME) => food.density match {
+        case Some(density) => VOLUME.defaultUnit
+            .convert(food, amount / density, to)
+        case None => Failure(new IncompleteDataException(food, "density"))
+      }
+      case (MASS, NUMBER) => food.massPerUnit match {
+        case Some(massPerUnit) => NUMBER.defaultUnit
+            .convert(food, amount / massPerUnit, to)
+        case None => Failure(new IncompleteDataException(food, "mass/unit"))
+      }
+      case (VOLUME, _) => food.density match {
+        case Some(density) => MASS.defaultUnit
+            .convert(food, amount * density, to)
+        case None => Failure(new IncompleteDataException(food, "density"))
+      }
+      case (NUMBER, _) => food.massPerUnit match {
+        case Some(massPerUnit) => MASS.defaultUnit.
+            convert(food, amount * massPerUnit, to)
+        case None => Failure(new IncompleteDataException(food, "mass/unit"))
+      }
+    }).map(_ * conversionRatio)
 }
 
 object MeasureUnit {