Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Markdown · 1.1 KiB · at 8b87e58

Write parseDuration, which converts a compact duration string such as "1h30m" into a number of milliseconds.

Grammar: the text is one or more segments written back to back with nothing between them. Each segment is an amount followed by a unit.

  • The amount is one or more ASCII digits (0 to 9). There is no sign, decimal point, or exponent.
  • The unit is one of d (86400000 ms), h (3600000 ms), m (minutes, 60000 ms), s (1000 ms), or ms (1 ms). Units are lowercase.
  • Each unit appears at most once, and units appear in descending order of size: d, h, m, s, ms. Units may be skipped, so "2d30s" is valid.
  • There is no whitespace anywhere, including at either end.

The result is the sum of amount times unit size over all segments. A zero amount is allowed.

Examples: "1h30m" is 5400000, "90s" is 90000, "2d4h" is 187200000, "250ms" is 250.

Any text that does not match the grammar, including the empty string and a bare number such as "5", fails with { kind: "invalid_duration", input }, where input is the text exactly as given.