(expr: Expression)
| 21 | * `UnitExpression` (string or JSON array) that `unit-data.ts` functions |
| 22 | * can work with. |
| 23 | */ |
| 24 | export function boxedToUnitExpression(expr: Expression): UnitExpression | null { |
| 25 | if (!expr) return null; |
| 26 | |
| 27 | // Simple symbol unit |
| 28 | if (isSymbol(expr)) return expr.symbol; |
| 29 | |
| 30 | if (!isFunction(expr)) return null; |
| 31 | |
| 32 | const op = expr.operator; |
| 33 | if (op === 'Multiply') { |
| 34 | const parts: UnitExpression[] = []; |
| 35 | for (const child of expr.ops) { |
| 36 | const c = boxedToUnitExpression(child); |
| 37 | if (!c) return null; |
| 38 | parts.push(c); |
| 39 | } |
| 40 | return ['Multiply', ...parts]; |
| 41 | } |
| 42 | |
| 43 | if (op === 'Divide') { |
| 44 | const a = boxedToUnitExpression(expr.op1); |
| 45 | const b = boxedToUnitExpression(expr.op2); |
| 46 | if (!a || !b) return null; |
| 47 | return ['Divide', a, b]; |
| 48 | } |
| 49 | |
| 50 | if (op === 'Power') { |
| 51 | const base = boxedToUnitExpression(expr.op1); |
| 52 | const exp = expr.op2?.re; |
| 53 | if (!base || exp === undefined) return null; |
| 54 | return ['Power', base, exp]; |
| 55 | } |
| 56 | |
| 57 | return null; |
| 58 | } |
| 59 | |
| 60 | export const UNITS_LIBRARY: SymbolDefinitions = { |
no test coverage detected