( ce: ComputeEngine, ops: ReadonlyArray<Expression> )
| 58 | function unitSymbol(q: QuantityExpr): string | null { |
| 59 | const u = q.op2; |
| 60 | return isSymbol(u) ? u.symbol : null; |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * Convert a (possibly `Measurement`) magnitude expression from its own unit to |
| 65 | * the target unit, preserving/scaling a `Measurement` error. Unit conversion |
| 66 | * is affine (`x → f·x + c`); the linear factor `f = convert(1) − convert(0)` |
| 67 | * removes any additive offset (so the error scales by `|f|` while the offset |
| 68 | * shifts the nominal only). Returns `undefined` if the units are incompatible. |
| 69 | */ |
| 70 | function convertMagnitude( |
| 71 | ce: ComputeEngine, |
| 72 | mag: Expression, |
| 73 | opSymbol: string | null, |
| 74 | opUE: ReturnType<typeof boxedToUnitExpression>, |
| 75 | targetSymbol: string | null, |
| 76 | targetUE: ReturnType<typeof boxedToUnitExpression> |
| 77 | ): Expression | undefined { |
| 78 | if (targetSymbol && opSymbol) { |
| 79 | if (opSymbol === targetSymbol) return mag; |
| 80 | const c0 = convertUnit(0, opSymbol, targetSymbol); |
| 81 | const c1 = convertUnit(1, opSymbol, targetSymbol); |
| 82 | if (c0 === null || c1 === null) return undefined; |
| 83 | return measurementAffine(ce, mag, c1 - c0, c0); |
| 84 | } |
| 85 | if (!opUE || !targetUE) return undefined; |
| 86 | const c0 = convertCompoundUnit(0, opUE, targetUE); |
| 87 | const c1 = convertCompoundUnit(1, opUE, targetUE); |
| 88 | if (c0 === null || c1 === null) return undefined; |
| 89 | return measurementAffine(ce, mag, c1 - c0, c0); |
| 90 | } |
| 91 | |
| 92 | // --------------------------------------------------------------------------- |
| 93 | // Quantity arithmetic |
| 94 | // --------------------------------------------------------------------------- |
| 95 | |
| 96 | /** |
| 97 | * Add Quantity expressions. All operands must be Quantities with |
| 98 | * compatible dimensions. The result uses the unit with the largest |
| 99 | * scale factor (e.g. `m` wins over `cm`, `km` wins over `m`). |
| 100 | */ |
| 101 | export function quantityAdd( |
| 102 | ce: ComputeEngine, |
| 103 | ops: ReadonlyArray<Expression> |
| 104 | ): Expression | undefined { |
| 105 | if (ops.length === 0) return undefined; |
| 106 | |
| 107 | // Collect all Quantity operands and cache their UnitExpressions |
| 108 | const quantities: QuantityExpr[] = []; |
| 109 | const unitExprs: ReturnType<typeof boxedToUnitExpression>[] = []; |
| 110 | for (const op of ops) { |
| 111 | if (!isQuantity(op)) return undefined; // non-Quantity mixed in |
| 112 | const ue = boxedToUnitExpression(op.op2); |
| 113 | if (!ue) return undefined; |
| 114 | quantities.push(op); |
| 115 | unitExprs.push(ue); |
| 116 | } |
| 117 | if (quantities.length === 0) return undefined; |
no test coverage detected