import { coreNutrientKeys } from "./nutrients.js"; // Label precision: 1 decimal from 10 up, 2 from 0.1, finer below. const round = (value) => { const places = value >= 10 ? 10 : value >= 0.1 ? 100 : 1e4; return Math.round(value * places) / places; }; /** * A product database row describes nutrition per 100 g (or 100 ml) plus a * serving size. This turns it into a per-serving food for the editor. * @param {{gtin: string, name?: string|null, brand?: string|null, * serving?: string|null, servingQty?: number|null, servingUnit?: string|null, * nutrients: Record, source?: string}} product */ export function productToFood(product) { const qty = product.servingQty > 0 && product.servingQty <= 5000 ? product.servingQty : null; const unit = product.servingUnit === "ml" ? "ml" : "g"; const factor = qty ? qty / 100 : 1; let serving = `100 ${unit}`; if (qty) { const text = (product.serving || "").trim(); // Prefer the label's own wording ("2/3 cup (55 g)") when it has any. serving = text && /[a-z]/i.test(text) && text.length <= 100 ? text : `${round(qty)} ${unit}`; } const nutrients = {}; const core = new Set(Object.values(coreNutrientKeys)); for (const [metric, key] of Object.entries(coreNutrientKeys)) nutrients[metric] = round((product.nutrients[key] || 0) * factor); const extra = {}; for (const [key, value] of Object.entries(product.nutrients)) if (!core.has(key) && Number.isFinite(value) && value >= 0) extra[key] = Math.min(round(value * factor), 100000); for (const metric of Object.keys(nutrients)) nutrients[metric] = Math.min(nutrients[metric], 100000); const brand = (product.brand || "").trim(); const title = (product.name || "").trim(); // "Cheerios" + "Cheerios Cereal" reads as "Cheerios Cereal", and a brand // owner such as "Coca-Cola Services SA/NV" never replaces "Coca-Cola". const overlaps = title.toLowerCase().includes(brand.toLowerCase()) || brand.toLowerCase().includes(title.toLowerCase()); const name = !title ? brand : !brand || overlaps ? title : `${brand} ${title}`; return { name: name.slice(0, 160) || undefined, brand: product.brand || undefined, serving, nutrients, ...(Object.keys(extra).length ? { extra } : {}), barcode: product.gtin, source: product.source, }; } /** USDA descriptions are often upper case; make them readable. */ export function titleCase(text) { if (!text || /[a-z]/.test(text)) return text; return text .toLowerCase() .replace( /(^|[\s(/&-])([a-z])/g, (_, gap, letter) => gap + letter.toUpperCase(), ); }