Deviopath › TypeScript

Convert Compound Units

Hard · Parsing

Write convert(value, from, to) for compound units built from the UNITS table in the starter, like "km/h", "m/s^2" or "kg*m/s^2".

- An expression is terms joined by *, with at most one /: terms before it multiply, ALL terms after it divide. A term is a unit name (letters), optionally followed by ^n with n a positive integer. No spaces.

- Factors and dimensions combine, e.g. km/h has factor 1000 / 3600 and dimension length 1, time -1.

- Errors (check from fully before to, terms left to right): "Invalid unit: <expr>" for more than one /, an empty term or a bad term; "Unknown unit: <name>" for a name that is not an own key of UNITS; "Cannot convert <from> to <to>" when the dimensions differ.

On success return { ok: true, value } rounded with Math.round(x * 10000) / 10000.

Next: Code Bracket Validator