diff --git a/pkg/db/ingredient.go b/pkg/db/ingredient.go index 366d9ca..99de69b 100644 --- a/pkg/db/ingredient.go +++ b/pkg/db/ingredient.go @@ -2,6 +2,8 @@ package db import ( "fmt" + "math" + "strings" ) type IngredientID uint64 @@ -83,3 +85,30 @@ func (db *DB) DeleteIngredient(i Ingredient) { panic(fmt.Errorf("tried to delete ingredient with ID (%d) but it doesn't exist", i.ID)) } } + +func (i Ingredient) DisplayAmount() string { + var f float32 + switch i.Units { + case COUNT: + f = i.Quantity + case GRAMS: + f = i.Quantity * i.Food.Mass + case LBS: + f = i.Quantity * i.Food.Mass / 454 + case OZ: + f = i.Quantity * i.Food.Mass / 28 + case ML: + f = i.Quantity * i.Food.Mass / i.Food.Density + case CUPS: + f = i.Quantity * i.Food.Mass / i.Food.Density / 250 + case TSP: + f = i.Quantity * i.Food.Mass / i.Food.Density / 5 + case TBSP: + f = i.Quantity * i.Food.Mass / i.Food.Density / 15 + case FLOZ: + f = i.Quantity * i.Food.Mass / i.Food.Density / 30 + default: + panic(i) + } + return strings.TrimSpace(fmt.Sprintf("%d %s", int(math.Round(float64(f))), i.Units.Abbreviation())) +} diff --git a/pkg/db/ingredient_test.go b/pkg/db/ingredient_test.go index 9e67b1a..54cd2a3 100644 --- a/pkg/db/ingredient_test.go +++ b/pkg/db/ingredient_test.go @@ -68,3 +68,24 @@ func TestSaveAndLoadIngredient(t *testing.T) { assert.NoError(err) require.Len(new_recipe.Ingredients, 0) } + +func TestDisplayAmount(t *testing.T) { + assert := assert.New(t) + db := get_test_db() + onion := get_food(db, 28) + + test_cases := []struct { + Ingredient + Expected string + }{ + {Ingredient{Quantity: 1, Units: COUNT, Food: onion}, "1"}, + {Ingredient{Quantity: 2, Units: COUNT, Food: onion}, "2"}, + {Ingredient{Quantity: 1.818, Units: GRAMS, Food: onion}, "400 g"}, + {Ingredient{Quantity: 9, Units: LBS, Food: onion}, "4 lbs"}, + {Ingredient{Quantity: 2, Units: ML, Food: onion}, "440 mL"}, + } + + for _, tc := range test_cases { + assert.Equal(tc.Ingredient.DisplayAmount(), tc.Expected) + } +} diff --git a/pkg/db/units.go b/pkg/db/units.go index 4d9bb09..322b1e1 100644 --- a/pkg/db/units.go +++ b/pkg/db/units.go @@ -3,7 +3,7 @@ package db type Units uint64 const ( - COUNT = Units(iota + 1) + COUNT = Units(iota + 1) // Start at 1 to match SQLite ID column GRAMS LBS OZ @@ -15,7 +15,7 @@ const ( ) var names = []string{"", "count", "grams", "pounds", "ounces", "milliliters", "cups", "teaspoons", "tablespoons", "fluid ounces"} -var abbreviations = []string{"", "ct", "g", "lbs", "oz", "mL", "cups", "tsp", "tbsp", "fl-oz"} +var abbreviations = []string{"", "", "g", "lbs", "oz", "mL", "cups", "tsp", "tbsp", "fl-oz"} func (u Units) Name() string { return names[u]