refactor: simplify parse ingredients code
This commit is contained in:
		| @@ -1,13 +1,23 @@ | ||||
| import { Signal } from "@preact/signals"; | ||||
| import type { Ingredient, IngredientGroup } from "@lib/recipeSchema.ts"; | ||||
| import { FunctionalComponent } from "preact"; | ||||
| import { unitsOfMeasure } from "@lib/parseIngredient.ts"; | ||||
|  | ||||
| function numberToString(num: number) { | ||||
| function formatAmount(num: number) { | ||||
|   if (num === 0) return ""; | ||||
|   return (Math.floor(num * 4) / 4).toString(); | ||||
| } | ||||
|  | ||||
| function stringToNumber(str: string) { | ||||
|   return parseFloat(str); | ||||
| function formatUnit(unit: string, amount: number) { | ||||
|   const unitKey = unit.toLowerCase() as keyof typeof unitsOfMeasure; | ||||
|   if (unitKey in unitsOfMeasure) { | ||||
|     if (amount > 1 && unitsOfMeasure[unitKey].plural !== undefined) { | ||||
|       return unitsOfMeasure[unitKey].plural; | ||||
|     } | ||||
|     return unitsOfMeasure[unitKey].short; | ||||
|   } else { | ||||
|     return unit; | ||||
|   } | ||||
| } | ||||
|  | ||||
| const Ingredient = ( | ||||
| @@ -20,7 +30,7 @@ const Ingredient = ( | ||||
| ) => { | ||||
|   const { name, quantity, unit } = ingredient; | ||||
|  | ||||
|   const parsedQuantity = stringToNumber(quantity); | ||||
|   const parsedQuantity = parseFloat(quantity); | ||||
|  | ||||
|   const finalAmount = (typeof parsedQuantity === "number" && amount) | ||||
|     ? (parsedQuantity / portion) * (amount?.value || 1) | ||||
| @@ -29,8 +39,10 @@ const Ingredient = ( | ||||
|   return ( | ||||
|     <tr key={key}> | ||||
|       <td class="pr-4 py-2"> | ||||
|         {numberToString(finalAmount || 0) + | ||||
|           (typeof unit === "string" ? unit : "")} | ||||
|         {formatAmount(finalAmount || 0)} | ||||
|         <span class="ml-0.5 opacity-50"> | ||||
|           {formatUnit(unit, finalAmount || 0)} | ||||
|         </span> | ||||
|       </td> | ||||
|       <td class="px-4 py-2">{name}</td> | ||||
|     </tr> | ||||
|   | ||||
		Reference in New Issue
	
	Block a user