split evalBin into percent/quantity arithmetic helpers

This commit is contained in:
Horizontal42 2026-07-29 14:14:49 +03:00
parent d66cad2dcf
commit 42f3611dca

View file

@ -199,12 +199,7 @@ function numericAdd(a: Quantity, b: Quantity, sign: 1 | -1): Quantity {
return qty(sign === 1 ? a.value.add(b.value) : a.value.sub(b.value), unit);
}
function evalBin(op: "plus" | "minus" | "mul" | "div" | "mod" | "pow", l: Value, r: Value, ctx: EvalCtx): Value {
// ---- dates
if (l.kind === "date" || r.kind === "date") return evalDateArith(op, l, r);
// ---- percent combinations
if (l.kind === "percent" || r.kind === "percent") {
function evalPercentArith(op: "plus" | "minus" | "mul" | "div" | "mod" | "pow", l: Value, r: Value): Value {
if (l.kind === "percent" && r.kind === "percent") {
switch (op) {
case "plus": return pct(l.value.add(r.value));
@ -232,10 +227,9 @@ function evalBin(op: "plus" | "minus" | "mul" | "div" | "mod" | "pow", l: Value,
: qty(q.value.pow(p.div(100)), q.unit);
default: throw new EvalError("bad percent op");
}
}
}
const a = l as Quantity;
const b = r as Quantity;
function evalQuantityArith(op: "plus" | "minus" | "mul" | "div" | "mod" | "pow", a: Quantity, b: Quantity, ctx: EvalCtx): Value {
switch (op) {
case "plus": return numericAdd(a, b, 1);
case "minus": return numericAdd(a, b, -1);
@ -281,6 +275,18 @@ function evalBin(op: "plus" | "minus" | "mul" | "div" | "mod" | "pow", l: Value,
}
}
function evalBin(op: "plus" | "minus" | "mul" | "div" | "mod" | "pow", l: Value, r: Value, ctx: EvalCtx): Value {
if (l.kind === "date" || r.kind === "date") {
return evalDateArith(op, l, r);
}
if (l.kind === "percent" || r.kind === "percent") {
return evalPercentArith(op, l, r);
}
return evalQuantityArith(op, l as Quantity, r as Quantity, ctx);
}
function evalBit(op: string, l: Value, r: Value): Value {
if (l.kind !== "quantity" || r.kind !== "quantity") throw new EvalError("bitwise needs integers");
if (!l.value.isFinite() || !r.value.isFinite()) throw new EvalError("bitwise needs finite integers");