Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AmyPfuNc4sCRfaF3oURXZz
303 lines
13 KiB
TypeScript
303 lines
13 KiB
TypeScript
// Formeln für Aufmaß und Mengenblatt (Stufe 3a, A22, Henning 21.10.2026): rechnen mit Kürzeln statt Zellbezügen,
|
||
// z. B. (B/2+UET)/cos(DN). Komma oder Punkt als Dezimalzeichen, Semikolon trennt Argumente: runden(x; 2).
|
||
// Winkel in Grad wie auf der Baustelle. Ein unbekanntes Kürzel ist ein Fehler, keine stille Null.
|
||
|
||
export type Wert = number | string;
|
||
|
||
export class FormelFehler extends Error {}
|
||
|
||
type Knoten =
|
||
| { t: "n"; v: number }
|
||
| { t: "s"; v: string }
|
||
| { t: "id"; name: string }
|
||
| { t: "f"; name: string; args: Knoten[] }
|
||
| { t: "op"; op: string; a: Knoten; b: Knoten }
|
||
| { t: "neg"; a: Knoten }
|
||
| { t: "pct"; a: Knoten };
|
||
|
||
type Token = { t: "n"; v: number } | { t: "s"; v: string } | { t: "id"; v: string } | { t: "o"; v: string };
|
||
|
||
const BUCHSTABE = /[\p{L}_]/u;
|
||
const ZEICHEN = /[\p{L}\p{N}_]/u;
|
||
|
||
function zerlege(f: string): Token[] {
|
||
const t: Token[] = [];
|
||
let i = 0;
|
||
while (i < f.length) {
|
||
const c = f[i]!;
|
||
if (/\s/.test(c)) { i++; continue; }
|
||
if (/\d/.test(c) || (c === "," || c === ".") && /\d/.test(f[i + 1] ?? "")) {
|
||
const m = /^\d*(?:[.,]\d+)?/.exec(f.slice(i))!;
|
||
t.push({ t: "n", v: Number(m[0].replace(",", ".")) });
|
||
i += m[0].length;
|
||
// „2,5 m“ oder „31°“: Einheit hinter einer Zahl überlesen
|
||
const e = /^\s*(?:°|m³|m²|m(?![\p{L}\p{N}_(]))/u.exec(f.slice(i));
|
||
if (e) i += e[0].length;
|
||
continue;
|
||
}
|
||
if (c === '"' || c === "„" || c === "“" || c === "'") {
|
||
const ende = f.slice(i + 1).search(/["“”']/);
|
||
if (ende < 0) throw new FormelFehler("Anführungszeichen nicht geschlossen");
|
||
t.push({ t: "s", v: f.slice(i + 1, i + 1 + ende) });
|
||
i += ende + 2;
|
||
continue;
|
||
}
|
||
if (BUCHSTABE.test(c)) {
|
||
let j = i + 1;
|
||
while (j < f.length && (ZEICHEN.test(f[j]!) || (f[j] === "." && BUCHSTABE.test(f[j + 1] ?? "")))) j++;
|
||
t.push({ t: "id", v: f.slice(i, j) });
|
||
i = j;
|
||
continue;
|
||
}
|
||
const zwei = f.slice(i, i + 2);
|
||
if (["<>", "!=", "<=", ">="].includes(zwei)) { t.push({ t: "o", v: zwei === "!=" ? "<>" : zwei }); i += 2; continue; }
|
||
const eins: Record<string, string> = { "×": "*", "·": "*", "≠": "<>", "≤": "<=", "≥": ">=", "−": "-", ",": ";" };
|
||
if ("+-*/^();%=<>".includes(c) || c in eins) { t.push({ t: "o", v: eins[c] ?? c }); i++; continue; }
|
||
throw new FormelFehler(`Zeichen „${c}“ ist nicht erlaubt`);
|
||
}
|
||
return t;
|
||
}
|
||
|
||
function parse(f: string): Knoten {
|
||
const t = zerlege(f);
|
||
let i = 0;
|
||
const ist = (v: string) => t[i]?.t === "o" && t[i]!.v === v;
|
||
const erwarte = (v: string) => {
|
||
if (!ist(v)) throw new FormelFehler(v === ")" ? "Klammer zu fehlt" : `„${v}“ fehlt`);
|
||
i++;
|
||
};
|
||
const ausdruck = (): Knoten => {
|
||
const a = summe();
|
||
for (const op of ["=", "<>", "<=", ">=", "<", ">"]) if (ist(op)) { i++; return { t: "op", op, a, b: summe() }; }
|
||
return a;
|
||
};
|
||
const summe = (): Knoten => {
|
||
let a = produkt();
|
||
while (ist("+") || ist("-")) { const op = (t[i++] as { v: string }).v; a = { t: "op", op, a, b: produkt() }; }
|
||
return a;
|
||
};
|
||
const produkt = (): Knoten => {
|
||
let a = vorzeichen();
|
||
while (ist("*") || ist("/")) { const op = (t[i++] as { v: string }).v; a = { t: "op", op, a, b: vorzeichen() }; }
|
||
return a;
|
||
};
|
||
const vorzeichen = (): Knoten => {
|
||
if (ist("-")) { i++; return { t: "neg", a: vorzeichen() }; }
|
||
if (ist("+")) { i++; return vorzeichen(); }
|
||
return potenz();
|
||
};
|
||
const potenz = (): Knoten => {
|
||
const a = prozent();
|
||
if (ist("^")) { i++; return { t: "op", op: "^", a, b: vorzeichen() }; }
|
||
return a;
|
||
};
|
||
const prozent = (): Knoten => {
|
||
let a = einfach();
|
||
while (ist("%")) { i++; a = { t: "pct", a }; }
|
||
return a;
|
||
};
|
||
const einfach = (): Knoten => {
|
||
const x = t[i];
|
||
if (!x) throw new FormelFehler(t.length ? "Formel unvollständig" : "leer");
|
||
i++;
|
||
if (x.t === "n") return { t: "n", v: x.v };
|
||
if (x.t === "s") return { t: "s", v: x.v };
|
||
if (x.t === "id") {
|
||
if (!ist("(")) return { t: "id", name: x.v };
|
||
i++;
|
||
const args: Knoten[] = [];
|
||
if (!ist(")")) {
|
||
args.push(ausdruck());
|
||
while (ist(";")) { i++; args.push(ausdruck()); }
|
||
}
|
||
erwarte(")");
|
||
return { t: "f", name: x.v.toLowerCase(), args };
|
||
}
|
||
if (x.v === "(") { const a = ausdruck(); erwarte(")"); return a; }
|
||
throw new FormelFehler(`„${x.v}“ an dieser Stelle geht nicht`);
|
||
};
|
||
const a = ausdruck();
|
||
if (i < t.length) {
|
||
const x = t[i]!;
|
||
throw new FormelFehler(x.t === "o" && x.v === ")" ? "Klammer auf fehlt" : `Nach „${f.slice(0, 20)}“ fehlt ein Rechenzeichen`);
|
||
}
|
||
return a;
|
||
}
|
||
|
||
const SPEICHER = new Map<string, Knoten | FormelFehler>();
|
||
function uebersetzt(f: string): Knoten {
|
||
let k = SPEICHER.get(f);
|
||
if (!k) {
|
||
try { k = parse(f); } catch (e) { k = e instanceof FormelFehler ? e : new FormelFehler(String(e)); }
|
||
if (SPEICHER.size > 5000) SPEICHER.clear();
|
||
SPEICHER.set(f, k);
|
||
}
|
||
if (k instanceof FormelFehler) throw k;
|
||
return k;
|
||
}
|
||
|
||
export interface Kontext {
|
||
/** Wert eines Kürzels; unbekannt → FormelFehler */
|
||
wert(name: string): Wert;
|
||
/** Spalte einer Liste („Wand.Breite“) für summe(), summewenn() und anzahl() */
|
||
spalte?(liste: string, spalte: string): Wert[];
|
||
/** Zeilenzahl einer Liste */
|
||
zeilen?(liste: string): number;
|
||
}
|
||
|
||
const GRAD = Math.PI / 180;
|
||
const zahl = (w: Wert, wo = "Wert"): number => {
|
||
if (typeof w === "number") return w;
|
||
const n = Number(w.trim().replace(",", "."));
|
||
if (w.trim() === "" ) return 0;
|
||
if (!Number.isFinite(n)) throw new FormelFehler(`${wo} „${w}“ ist keine Zahl`);
|
||
return n;
|
||
};
|
||
const gleich = (a: Wert, b: Wert) =>
|
||
typeof a === "string" || typeof b === "string" ? String(a).trim().toLowerCase() === String(b).trim().toLowerCase() : Math.abs(a - b) < 1e-9;
|
||
const stellen = (args: number[]) => 10 ** Math.round(args[1] ?? 0);
|
||
|
||
// gleiche Namen wie in Excel gehen auch, damit Formeln aus den Musterpositionen passen
|
||
const NAMEN: Record<string, string> = {
|
||
roundup: "aufrunden", obergrenze: "aufrunden", rounddown: "abrunden", untergrenze: "abrunden", round: "runden", sqrt: "wurzel",
|
||
if: "wenn", and: "und", or: "oder", not: "nicht", choose: "wahl", sum: "summe", count: "anzahl", sumif: "summewenn", countif: "anzahlwenn",
|
||
atan: "arctan", asin: "arcsin", acos: "arccos", mod: "rest", int: "ganzzahl",
|
||
};
|
||
export const FUNKTIONEN = ["aufrunden", "abrunden", "runden", "min", "max", "abs", "wurzel", "sin", "cos", "tan", "arcsin", "arccos", "arctan", "pi",
|
||
"wenn", "und", "oder", "nicht", "wahl", "summe", "anzahl", "summewenn", "anzahlwenn", "rest", "ganzzahl"];
|
||
|
||
function rechne(k: Knoten, x: Kontext): Wert {
|
||
switch (k.t) {
|
||
case "n": case "s": return k.v;
|
||
case "id":
|
||
if (k.name.includes(".")) throw new FormelFehler(`„${k.name}“ ist eine Listenspalte; nutze summe(${k.name})`);
|
||
return x.wert(k.name);
|
||
case "neg": return -zahl(rechne(k.a, x));
|
||
case "pct": return zahl(rechne(k.a, x)) / 100;
|
||
case "op": {
|
||
const a = rechne(k.a, x), b = rechne(k.b, x);
|
||
switch (k.op) {
|
||
case "=": return gleich(a, b) ? 1 : 0;
|
||
case "<>": return gleich(a, b) ? 0 : 1;
|
||
case "<": return zahl(a) < zahl(b) - 1e-12 ? 1 : 0;
|
||
case ">": return zahl(a) > zahl(b) + 1e-12 ? 1 : 0;
|
||
case "<=": return zahl(a) <= zahl(b) + 1e-12 ? 1 : 0;
|
||
case ">=": return zahl(a) >= zahl(b) - 1e-12 ? 1 : 0;
|
||
case "+": return zahl(a) + zahl(b);
|
||
case "-": return zahl(a) - zahl(b);
|
||
case "*": return zahl(a) * zahl(b);
|
||
case "/": { const n = zahl(b); if (n === 0) throw new FormelFehler("Teilen durch 0"); return zahl(a) / n; }
|
||
case "^": return zahl(a) ** zahl(b);
|
||
}
|
||
throw new FormelFehler(`Rechenzeichen ${k.op}`);
|
||
}
|
||
case "f": return funktion(NAMEN[k.name] ?? k.name, k.args, x);
|
||
}
|
||
}
|
||
|
||
/** Werte einer Listenspalte, oder einzelne Zahlen, für summe() und Co. */
|
||
function sammle(args: Knoten[], x: Kontext): Wert[] {
|
||
const aus: Wert[] = [];
|
||
for (const a of args) {
|
||
if (a.t === "id" && a.name.includes(".")) {
|
||
const [l, s] = a.name.split(".") as [string, string];
|
||
if (!x.spalte) throw new FormelFehler(`Liste „${l}“ gibt es hier nicht`);
|
||
aus.push(...x.spalte(l, s));
|
||
} else aus.push(rechne(a, x));
|
||
}
|
||
return aus;
|
||
}
|
||
|
||
function funktion(name: string, args: Knoten[], x: Kontext): Wert {
|
||
const n = () => args.map((a) => zahl(rechne(a, x)));
|
||
const genau = (anzahl: number, bis = anzahl) => {
|
||
if (args.length < anzahl || args.length > bis) throw new FormelFehler(`${name}() braucht ${anzahl === bis ? anzahl : `${anzahl} bis ${bis}`} ${bis === 1 ? "Wert" : "Werte"}`);
|
||
};
|
||
switch (name) {
|
||
case "aufrunden": { genau(1, 2); const v = n(), f = stellen(v); return Math.ceil(v[0]! * f - 1e-9) / f; }
|
||
case "abrunden": { genau(1, 2); const v = n(), f = stellen(v); return Math.floor(v[0]! * f + 1e-9) / f; }
|
||
case "runden": { genau(1, 2); const v = n(), f = stellen(v); return Math.sign(v[0]!) * Math.round(Math.abs(v[0]!) * f + 1e-9) / f; }
|
||
case "ganzzahl": genau(1); return Math.trunc(n()[0]!);
|
||
case "rest": { genau(2); const [a, b] = n() as [number, number]; if (b === 0) throw new FormelFehler("Teilen durch 0"); return a - b * Math.floor(a / b); }
|
||
case "min": case "max": {
|
||
const v = sammle(args, x).map((w) => zahl(w));
|
||
if (!v.length) throw new FormelFehler(`${name}() braucht Werte`);
|
||
return name === "min" ? Math.min(...v) : Math.max(...v);
|
||
}
|
||
case "abs": genau(1); return Math.abs(n()[0]!);
|
||
case "wurzel": { genau(1); const v = n()[0]!; if (v < 0) throw new FormelFehler("Wurzel aus einer negativen Zahl"); return Math.sqrt(v); }
|
||
case "sin": genau(1); return Math.sin(n()[0]! * GRAD);
|
||
case "cos": genau(1); return Math.cos(n()[0]! * GRAD);
|
||
case "tan": genau(1); return Math.tan(n()[0]! * GRAD);
|
||
case "arcsin": genau(1); return Math.asin(n()[0]!) / GRAD;
|
||
case "arccos": genau(1); return Math.acos(n()[0]!) / GRAD;
|
||
case "arctan": genau(1); return Math.atan(n()[0]!) / GRAD;
|
||
case "pi": genau(0); return Math.PI;
|
||
case "wenn": genau(2, 3); return zahl(rechne(args[0]!, x)) !== 0 ? rechne(args[1]!, x) : args[2] ? rechne(args[2], x) : 0;
|
||
case "und": return args.every((a) => zahl(rechne(a, x)) !== 0) ? 1 : 0;
|
||
case "oder": return args.some((a) => zahl(rechne(a, x)) !== 0) ? 1 : 0;
|
||
case "nicht": genau(1); return zahl(rechne(args[0]!, x)) === 0 ? 1 : 0;
|
||
case "wahl": {
|
||
if (args.length < 2) throw new FormelFehler("wahl() braucht eine Nummer und Werte");
|
||
const i = Math.round(zahl(rechne(args[0]!, x)));
|
||
if (i < 1 || i >= args.length) throw new FormelFehler(`wahl(): ${i} gibt es nicht`);
|
||
return rechne(args[i]!, x);
|
||
}
|
||
case "summe": return sammle(args, x).reduce((s: number, w) => s + zahl(w), 0);
|
||
case "anzahl": {
|
||
if (args.length === 1 && args[0]!.t === "id" && !args[0]!.name.includes(".")) {
|
||
const l = args[0]!.name;
|
||
if (x.zeilen) { const z = x.zeilen(l); if (z >= 0) return z; }
|
||
}
|
||
return sammle(args, x).filter((w) => String(w).trim() !== "").length;
|
||
}
|
||
case "summewenn": case "anzahlwenn": {
|
||
const mitSumme = name === "summewenn";
|
||
genau(mitSumme ? 3 : 2);
|
||
const werte = mitSumme ? sammle([args[0]!], x) : [];
|
||
const kriterien = sammle([args[mitSumme ? 1 : 0]!], x);
|
||
const soll = rechne(args[mitSumme ? 2 : 1]!, x);
|
||
let s = 0;
|
||
kriterien.forEach((k, i) => { if (gleich(k, soll)) s += mitSumme ? zahl(werte[i] ?? 0) : 1; });
|
||
return s;
|
||
}
|
||
}
|
||
throw new FormelFehler(`Funktion „${name}“ gibt es nicht`);
|
||
}
|
||
|
||
/** Eine Formel ausrechnen; Fehler als FormelFehler */
|
||
export function berechne(formel: string, x: Kontext): Wert {
|
||
return rechne(uebersetzt(formel), x);
|
||
}
|
||
|
||
/** Nur prüfen, ob die Formel lesbar ist (ohne Kürzel aufzulösen) */
|
||
export function formelFehler(formel: string): string | null {
|
||
try { uebersetzt(formel); return null; } catch (e) { return (e as Error).message; }
|
||
}
|
||
|
||
/** Alle Kürzel, die eine Formel benutzt (ohne Funktionsnamen) */
|
||
export function kuerzelIn(formel: string): string[] {
|
||
try {
|
||
return zerlege(formel).filter((t, i, a) => t.t === "id" && !(a[i + 1]?.t === "o" && a[i + 1]!.v === "(")).map((t) => t.v as string);
|
||
} catch { return []; }
|
||
}
|
||
|
||
export const KUERZEL = /^[\p{L}_][\p{L}\p{N}_]*$/u;
|
||
|
||
/** Kürzel in einer Formel umbenennen (nicht in Texten in Anführungszeichen, nicht hinter einem Punkt) */
|
||
export function benenneUm(formel: string, alt: string, neu: string): string {
|
||
if (!alt || !neu || alt === neu) return formel;
|
||
const teile = formel.split(/(["„“'][^"“”']*["“”'])/);
|
||
return teile.map((t, i) => (i % 2 ? t : t.replace(new RegExp(`(?<![\\p{L}\\p{N}_.])${alt.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\p{L}\\p{N}_(])`, "gu"), neu))).join("");
|
||
}
|
||
|
||
/** Zahl für Mengenblatt und Texte: ganze Zahlen ohne Komma, sonst bis 3 Stellen, mindestens 2 */
|
||
export function zahlDeutsch(n: number, einheit?: string | null): string {
|
||
if (!Number.isFinite(n)) return "–";
|
||
const ganz = Math.abs(n - Math.round(n)) < 1e-9;
|
||
const flaeche = einheit && /^(m|m²|m³|lfm|h)$/.test(einheit);
|
||
const r = Math.round(n * 1000) / 1000;
|
||
const min = ganz && !flaeche ? 0 : 2;
|
||
return r.toLocaleString("de-DE", { minimumFractionDigits: min, maximumFractionDigits: Math.max(min, 3) });
|
||
}
|