( expr: UnitExpression )
| 418 | const siValue = (value + fromOffset) * from.scale; |
| 419 | return siValue / to.scale - toOffset; |
| 420 | } |
| 421 | |
| 422 | // --------------------------------------------------------------------------- |
| 423 | // Compound unit expressions |
| 424 | // --------------------------------------------------------------------------- |
| 425 | |
| 426 | /** |
| 427 | * A MathJSON-like unit expression: either a string (simple unit symbol) or |
| 428 | * an array like `["Divide", "m", "s"]`. |
| 429 | */ |
| 430 | export type UnitExpression = string | [string, ...any[]]; |
| 431 | |
| 432 | /** |
| 433 | * Compute the dimension vector for a MathJSON unit expression. |
| 434 | * |
| 435 | * - If `expr` is a string, delegates to `getUnitDimension`. |
| 436 | * - `["Multiply", a, b, ...]` — adds dimension vectors component-wise. |
| 437 | * - `["Divide", a, b]` — subtracts b's dimension from a's. |
| 438 | * - `["Power", base, exp]` — multiplies base dimension by exp. |
| 439 | * |
| 440 | * Returns `null` if any component is unrecognised. |
| 441 | */ |
| 442 | export function getExpressionDimension( |
| 443 | expr: UnitExpression |
| 444 | ): DimensionVector | null { |
| 445 | if (typeof expr === 'string') return getUnitDimension(expr); |
| 446 | |
| 447 | if (!Array.isArray(expr) || expr.length < 2) return null; |
| 448 | |
| 449 | const op = expr[0]; |
| 450 | |
| 451 | if (op === 'Multiply') { |
| 452 | const result: DimensionVector = [0, 0, 0, 0, 0, 0, 0, 0]; |
| 453 | for (let i = 1; i < expr.length; i++) { |
| 454 | const d = getExpressionDimension(expr[i]); |
| 455 | if (!d) return null; |
| 456 | for (let j = 0; j < 8; j++) result[j] += d[j]; |
| 457 | } |
| 458 | return result; |
| 459 | } |
no test coverage detected