Add helper function to format ingredient amounts

This commit is contained in:
Alessio 2024-11-18 14:47:20 -08:00
parent e2392efe40
commit 2670af3eb7
3 changed files with 52 additions and 2 deletions

View File

@ -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()))
}

View File

@ -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)
}
}

View File

@ -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]