Files
lunch/lib/units.ts
T
kai 1d875fa02e
release / which version (push) Successful in 6s
release / olares chart · sanity (push) Successful in 6s
release / app (push) Successful in 1m11s
release / tag and release (push) Successful in 3s
26.11.39: Löffel und Gebinde (#40)
2026-11-07 16:39:04 +00:00

183 lines
8.2 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Mengen: gespeichert immer in Basiseinheiten pro Portion (g, ml, Stück —
// CLAUDE.md, Regel 2). Hier und nur hier wird umgerechnet: hochrechnen,
// lesbar anzeigen, Eingaben aus Küchenmaßen in Basiseinheiten bringen.
export type BaseUnit = "g" | "ml" | "piece";
/** Gebinde, in denen man kauft: Dose, Glas, Packung, Bund (26.11.39). */
export const PACK_KINDS = ["can", "jar", "pack", "bunch"] as const;
export type PackKind = (typeof PACK_KINDS)[number];
/** Küchenmaße, die ein Rezept so anzeigt, wie sie eingegeben wurden (26.11.39). */
export const KITCHEN_UNITS = ["tbsp", "tsp", "pinch", ...PACK_KINDS] as const;
export type KitchenUnit = (typeof KITCHEN_UNITS)[number];
export const isPackKind = (u: string): u is PackKind => (PACK_KINDS as readonly string[]).includes(u);
export const isKitchenUnit = (u: string): u is KitchenUnit => (KITCHEN_UNITS as readonly string[]).includes(u);
/** Maße, die man tippt oder in Rezepten liest. */
export type InputUnit = BaseUnit | "kg" | "l" | "cl" | "tbsp" | "tsp" | "pinch" | "cup" | PackKind;
/** Hochrechnen: Menge pro Portion × Portionen. */
export function scale(qtyPerPortion: number, portions: number): number {
return qtyPerPortion * portions;
}
// Küchenmaße in Basiseinheiten. Löffel und Tassen sind Volumen; für feste
// Zutaten (Einheit g) gilt eine mittlere Dichte — genau genug für ein
// Familienrezept, und die Planerin sieht und korrigiert die Menge.
const VOLUME_ML: Partial<Record<InputUnit, number>> = { ml: 1, cl: 10, l: 1000, tbsp: 15, tsp: 5, cup: 240, pinch: 0.5 };
const SOLID_G: Partial<Record<InputUnit, number>> = { g: 1, kg: 1000, tbsp: 12, tsp: 4, cup: 150, pinch: 0.5 };
/**
* Eingabe in die Basiseinheit der Zutat bringen. Gibt null zurück, wenn die
* Maße nicht zusammenpassen (z. B. „200 g“ Eier) — dann fragt die Oberfläche nach.
* Ein Gebinde braucht seine Größe in der Basiseinheit („1 Dose“ × 400 g).
*/
export function toBase(qty: number, unit: InputUnit, base: BaseUnit, packSize?: number | null): number | null {
if (!Number.isFinite(qty) || qty < 0) return null;
if (isPackKind(unit)) return packSize && packSize > 0 ? qty * packSize : null;
if (base === "piece") return unit === "piece" ? qty : null;
if (unit === "piece") return null;
if (base === "ml") {
const f = VOLUME_ML[unit] ?? (unit === "g" ? 1 : unit === "kg" ? 1000 : undefined); // g ≈ ml bei Flüssigem
return f === undefined ? null : qty * f;
}
const f = SOLID_G[unit] ?? (unit === "ml" ? 1 : unit === "l" ? 1000 : unit === "cl" ? 10 : undefined);
return f === undefined ? null : qty * f;
}
const FRACTIONS: [number, string][] = [
[0.25, "¼"],
[1 / 3, "⅓"],
[0.5, "½"],
[2 / 3, "⅔"],
[0.75, "¾"],
];
/** Stückzahlen in Küchenbrüchen: 0,5 → ½, 1,25 → 1¼; sonst auf eine Stelle. */
function pieces(qty: number, locale: string): string {
const whole = Math.floor(qty + 1e-9);
const rest = qty - whole;
if (rest < 0.05) return String(whole || (qty > 0 ? "<1" : "0"));
if (rest > 0.95) return String(whole + 1);
for (const [value, glyph] of FRACTIONS) {
if (Math.abs(rest - value) < 0.05) return whole ? `${whole}${glyph}` : glyph;
}
return new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).format(qty);
}
/** Auf eine Größe runden, die man in der Küche abwiegt. */
function roundMeasure(value: number): number {
if (value < 5) return Math.round(value * 2) / 2;
if (value < 50) return Math.round(value);
if (value < 250) return Math.round(value / 5) * 5;
return Math.round(value / 10) * 10;
}
export type Formatted = { amount: string; unit: string };
/**
* Für die Anzeige: 1500 g → 1,5 kg, 250 ml → 250 ml, 0,5 Stück → ½.
* `unit` ist ein kurzes Zeichen ("g", "kg", "ml", "l") oder leer bei Stück —
* das Wort für Stück liefert die Oberfläche selbst (Plural je Sprache).
*/
export function formatQuantity(qty: number, unit: BaseUnit, locale = "de"): Formatted {
const nf = (v: number, digits: number) => new Intl.NumberFormat(locale, { maximumFractionDigits: digits }).format(v);
if (unit === "piece") return { amount: pieces(qty, locale), unit: "" };
const rounded = roundMeasure(qty);
if (rounded >= 1000) return { amount: nf(Math.round(rounded / 100) / 10, 1), unit: unit === "g" ? "kg" : "l" };
return { amount: nf(rounded, 1), unit };
}
/** Menge in Basiseinheit zurück in das Küchenmaß, in dem sie eingegeben wurde (fürs Bearbeiten). */
export function fromBase(qty: number, unit: KitchenUnit, base: BaseUnit, packSize?: number | null): number | null {
if (isPackKind(unit)) return packSize && packSize > 0 ? qty / packSize : null;
const f = base === "ml" ? VOLUME_ML[unit] : base === "g" ? SOLID_G[unit] : undefined;
return f ? qty / f : null;
}
/** Löffel und Prisen in Küchenbrüchen; ein Löffel wird nicht genauer als ein halber. */
function spoons(qty: number, locale: string): string {
return pieces(qty < 0.5 ? qty : Math.round(qty * 2) / 2, locale);
}
export type KitchenFormatted = {
/** Vorn stehende Zahl mit Maß: „2 EL“, „400 g“, „6“. */
main: string;
/** In Klammern dahinter: „30 ml“, „1 Dose“ — leer, wenn nichts zu sagen ist. */
extra: string;
};
/**
* Anzeige mit Küchenmaß (Kai, 26.11.39): Löffel vorn, Gramm in Klammern —
* „2 EL (30 ml)“; Gebinde hinten, Gramm vorn — „400 g (1 Dose)“. Ohne Küchenmaß
* oder ohne bekannte Gebindegröße wie bisher. `word` liefert das Wort in der
* Sprache („Dose“/„Dosen“), `count` entscheidet über Einzahl oder Mehrzahl.
*/
export function formatKitchen(
qty: number,
base: BaseUnit,
display: KitchenUnit | null | undefined,
packSize: number | null | undefined,
locale: string,
word: (unit: KitchenUnit, count: number) => string,
): KitchenFormatted {
const plain = formatQuantity(qty, base, locale);
const plainText = `${plain.amount}${plain.unit ? ` ${plain.unit}` : ""}`;
if (!display) return { main: plainText, extra: "" };
const n = fromBase(qty, display, base, packSize);
if (n === null) return { main: plainText, extra: "" };
if (isPackKind(display)) {
// Ein Achtel Packung Butter hilft niemandem — dann nur Gramm.
if (n < 0.25 - 1e-9) return { main: plainText, extra: "" };
const count = pieces(n, locale);
return { main: plainText, extra: `${count} ${word(display, n)}` };
}
const count = spoons(n, locale);
// Eine Prise wiegt nichts, was man nachwiegen würde — ohne Klammer.
return { main: `${count} ${word(display, n)}`, extra: display === "pinch" || base === "piece" ? "" : plainText };
}
/**
* Küchenmaß für Mengen ohne eingegebenes Maß (ältere Gerichte, Vorlagen): Gebinde,
* wenn es mindestens ein Viertel ist; Löffel, wenn es ½ bis 8 Löffel sind. Prisen
* nie von selbst. Entschieden für die Menge des ganzen Rezepts, nicht je Portion.
*/
export function impliedKitchenUnit(
qty: number,
base: BaseUnit,
kitchenUnit: KitchenUnit | null | undefined,
packKind: PackKind | null | undefined,
packSize: number | null | undefined,
): KitchenUnit | null {
if (packKind && packSize) {
const n = qty / packSize;
if (n >= 0.25 - 1e-9) return packKind;
}
if (kitchenUnit === "tbsp" || kitchenUnit === "tsp") {
const n = fromBase(qty, kitchenUnit, base);
if (n !== null && n >= 0.5 - 1e-9 && n <= 8 + 1e-9) return kitchenUnit;
}
return null;
}
/** Für die Einkaufsliste: Stück immer aufrunden (½ Zwiebel kauft man nicht). */
export function shoppingQuantity(qty: number, unit: BaseUnit): number {
return unit === "piece" ? Math.ceil(qty - 1e-9) : qty;
}
/** Deutsche und englische Zahlen lesen: „1,5“, „1.5“, „1 1/2“, „½“. */
export function parseNumber(text: string): number | null {
const t = text.trim().replace(/\s+/g, " ");
const glyph: Record<string, number> = { "¼": 0.25, "½": 0.5, "¾": 0.75, "⅓": 1 / 3, "⅔": 2 / 3 };
const m = t.match(/^(\d+)?\s*([¼½¾⅓⅔])$/);
if (m) return Number(m[1] ?? 0) + glyph[m[2]!]!;
const mixed = t.match(/^(\d+) (\d+)\/(\d+)$/);
if (mixed) return Number(mixed[1]) + Number(mixed[2]) / Number(mixed[3]);
const frac = t.match(/^(\d+)\/(\d+)$/);
if (frac) return Number(frac[1]) / Number(frac[2]);
const n = Number(t.replace(",", "."));
return Number.isFinite(n) && t !== "" ? n : null;
}