Skip to content

Commit 8711103

Browse files
committed
feat(units): serialize in ASCIIMath
1 parent 38c10de commit 8711103

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

src/compute-engine/boxed-expression/ascii-math.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,25 @@ import { isFunction, isSymbol, isString, isNumber } from './type-guards';
66
/** Helper type for expressions known to be function expressions (in operator/function callbacks) */
77
type FnExpr = Expression & FunctionInterface;
88

9+
/** Serialize a unit expression to a human-readable string like "m/s^2". */
10+
function unitToString(expr: Expression): string {
11+
if (isSymbol(expr)) return expr.symbol;
12+
if (isNumber(expr)) return String(expr.re);
13+
if (!isFunction(expr)) return '';
14+
const op = expr.operator;
15+
if (op === 'Divide')
16+
return `${unitToString(expr.op1)}/${unitToString(expr.op2)}`;
17+
if (op === 'Multiply')
18+
return expr.ops.map(unitToString).join('\u22C5');
19+
if (op === 'Power') {
20+
const exp = expr.op2?.re;
21+
return exp !== undefined
22+
? `${unitToString(expr.op1)}^${exp}`
23+
: unitToString(expr.op1);
24+
}
25+
return '';
26+
}
27+
928
export type AsciiMathSerializer = (
1029
expr: Expression,
1130
precedence?: number
@@ -263,6 +282,11 @@ const FUNCTIONS: Record<
263282
Dim: 'dim',
264283
Mod: 'mod',
265284

285+
Quantity: (expr_, serialize) => {
286+
const expr = expr_ as FnExpr;
287+
return `${serialize(expr.op1)} ${unitToString(expr.op2)}`;
288+
},
289+
266290
GCD: 'gcd',
267291
LCM: 'lcm',
268292
Lub: 'lub',

0 commit comments

Comments
 (0)